✨ pydantic character builder
This commit is contained in:
@@ -0,0 +1,46 @@
|
|||||||
|
import pathlib
|
||||||
|
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
from base_mob import BaseMob
|
||||||
|
|
||||||
|
|
||||||
|
class CharacterModel(BaseModel):
|
||||||
|
name: str
|
||||||
|
max_pv: int
|
||||||
|
current_pv: int
|
||||||
|
strength: int
|
||||||
|
protection: int
|
||||||
|
speed: int
|
||||||
|
mob_type: int
|
||||||
|
|
||||||
|
|
||||||
|
def save_character(character: BaseMob) -> str:
|
||||||
|
filename = f'{character.name}.json'
|
||||||
|
character_model = CharacterModel(
|
||||||
|
name=character.name,
|
||||||
|
max_pv=character.max_pv,
|
||||||
|
current_pv=character.current_pv,
|
||||||
|
strength=character.strength,
|
||||||
|
protection=character.protection,
|
||||||
|
speed=character.speed,
|
||||||
|
mob_type=character.mob_type
|
||||||
|
)
|
||||||
|
pathlib.Path(filename).write_text(
|
||||||
|
data=character_model.model_dump_json(indent=4),
|
||||||
|
encoding='utf-8'
|
||||||
|
)
|
||||||
|
return filename
|
||||||
|
|
||||||
|
|
||||||
|
def load_character(name: str) -> BaseMob | None:
|
||||||
|
json_data = pathlib.Path(f'{name}.json').read_text(encoding='utf-8')
|
||||||
|
character_model = CharacterModel.model_validate_json(json_data)
|
||||||
|
return BaseMob(
|
||||||
|
name=character_model.name,
|
||||||
|
max_pv=character_model.max_pv,
|
||||||
|
strength=character_model.strength,
|
||||||
|
protection=character_model.protection,
|
||||||
|
speed=character_model.speed,
|
||||||
|
mob_type=character_model.mob_type,
|
||||||
|
)
|
||||||
Reference in New Issue
Block a user