2026-01-15 12:43:40 +01:00
|
|
|
from pathlib import Path
|
|
|
|
|
import json
|
|
|
|
|
import shutil
|
|
|
|
|
|
|
|
|
|
from wargame_campaign.model.player import Player
|
|
|
|
|
|
|
|
|
|
class Model:
|
|
|
|
|
def __init__(self):
|
|
|
|
|
self.players = {}
|
|
|
|
|
data_file_path = Path("data/warmachron.json")
|
|
|
|
|
self.load_data(data_file_path)
|
2026-01-16 18:13:01 +01:00
|
|
|
self.save_data(data_file_path)
|
2026-01-15 12:43:40 +01:00
|
|
|
|
|
|
|
|
def load_data(self, data_file_path):
|
|
|
|
|
if not data_file_path.exists() or data_file_path.stat().st_size == 0:
|
|
|
|
|
pass # Create empty json
|
|
|
|
|
try:
|
|
|
|
|
with open(data_file_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"]:
|
2026-01-16 18:13:01 +01:00
|
|
|
# placeholder
|
2026-01-15 12:43:40 +01:00
|
|
|
pass
|
|
|
|
|
except json.JSONDecodeError:
|
|
|
|
|
raise RuntimeError("Data file is corrupted")
|
|
|
|
|
|
|
|
|
|
def save_data(self, data_file_path):
|
|
|
|
|
if data_file_path.exists():
|
|
|
|
|
shutil.copy(data_file_path, data_file_path.with_suffix(".json.bak"))
|
|
|
|
|
data = {}
|
2026-01-16 18:13:01 +01:00
|
|
|
data['version'] = "1.0"
|
2026-01-15 12:43:40 +01:00
|
|
|
data['players'] = []
|
2026-01-16 18:13:01 +01:00
|
|
|
data['wars'] = []
|
|
|
|
|
for player in self.players.values():
|
2026-01-15 12:43:40 +01:00
|
|
|
data['players'].append(player.toDict())
|
|
|
|
|
with open(data_file_path, "w", encoding="utf-8") as f:
|
|
|
|
|
json.dump(data, f, indent=2)
|
|
|
|
|
|
|
|
|
|
def add_player(self, name):
|
|
|
|
|
player = Player(name)
|
|
|
|
|
self.players[player.id] = player
|
|
|
|
|
return player
|
|
|
|
|
|
|
|
|
|
def get_player(self, id):
|
|
|
|
|
return self.players[id]
|
|
|
|
|
|
|
|
|
|
def update_player(self, id, name):
|
|
|
|
|
player = self.get_player(id)
|
|
|
|
|
player.set_name(name)
|
|
|
|
|
|
|
|
|
|
def delete_player(self, id):
|
|
|
|
|
del self.players[id]
|
|
|
|
|
|
2026-01-16 18:13:01 +01:00
|
|
|
def get_all_players(self) -> list[Player]:
|
|
|
|
|
return list(self.players.values())
|
|
|
|
|
|