save & load wars
This commit is contained in:
parent
1218f32752
commit
dc854b4065
5 changed files with 52 additions and 50 deletions
|
|
@ -15,8 +15,6 @@ class Model:
|
|||
def new(self):
|
||||
self.players.clear()
|
||||
self.wars.clear()
|
||||
# self.campaigns.clear()
|
||||
# self.rounds.clear()
|
||||
|
||||
def load(self, path: Path):
|
||||
self.players.clear()
|
||||
|
|
@ -32,24 +30,25 @@ class Model:
|
|||
try:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
for player in data["players"] :
|
||||
saved_player = Player.fromDict(player["id"], player['name'])
|
||||
self.players[saved_player.id] = saved_player
|
||||
for war in data["wars"]:
|
||||
# placeholder
|
||||
pass
|
||||
self.players.clear()
|
||||
self.wars.clear()
|
||||
for p in data.get("players", []):
|
||||
player = Player.fromDict(p)
|
||||
self.players[player.id] = player
|
||||
for w in data.get("wars", []):
|
||||
war = War.fromDict(w)
|
||||
self.wars[war.id] = war
|
||||
except json.JSONDecodeError:
|
||||
raise RuntimeError("Data file is corrupted")
|
||||
|
||||
def _save_data(self, path: Path):
|
||||
if path.exists():
|
||||
shutil.copy(path, path.with_suffix(".json.bak"))
|
||||
data = {}
|
||||
data['version'] = "1.0"
|
||||
data['players'] = []
|
||||
data['wars'] = []
|
||||
for player in self.players.values():
|
||||
data['players'].append(player.toDict())
|
||||
data = {
|
||||
"version": "1.0",
|
||||
"players": [p.toDict() for p in self.players.values()],
|
||||
"wars": [w.toDict() for w in self.wars.values()]
|
||||
}
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, indent=2)
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue