Save the inventory of the player when saving the game, fixes #33

This commit is contained in:
Yohann D'ANELLO 2020-12-05 14:35:59 +01:00
parent f887a1f0aa
commit c38f8cdc53
2 changed files with 15 additions and 2 deletions

View File

@ -19,7 +19,8 @@ class Player(FightingEntity):
def __init__(self, name: str = "player", maxhealth: int = 20, def __init__(self, name: str = "player", maxhealth: int = 20,
strength: int = 5, intelligence: int = 1, charisma: int = 1, strength: int = 5, intelligence: int = 1, charisma: int = 1,
dexterity: int = 1, constitution: int = 1, level: int = 1, dexterity: int = 1, constitution: int = 1, level: int = 1,
current_xp: int = 0, max_xp: int = 10, *args, **kwargs) \ current_xp: int = 0, max_xp: int = 10, inventory: list = None,
*args, **kwargs) \
-> None: -> None:
super().__init__(name=name, maxhealth=maxhealth, strength=strength, super().__init__(name=name, maxhealth=maxhealth, strength=strength,
intelligence=intelligence, charisma=charisma, intelligence=intelligence, charisma=charisma,
@ -27,7 +28,12 @@ class Player(FightingEntity):
level=level, *args, **kwargs) level=level, *args, **kwargs)
self.current_xp = current_xp self.current_xp = current_xp
self.max_xp = max_xp self.max_xp = max_xp
self.inventory = list() self.inventory = inventory if inventory else list()
for i in range(len(self.inventory)):
if isinstance(self.inventory[i], dict):
entity_classes = self.get_all_entity_classes_in_a_dict()
item_class = entity_classes[self.inventory[i]["type"]]
self.inventory[i] = item_class(**self.inventory[i])
self.paths = dict() self.paths = dict()
def move(self, y: int, x: int) -> None: def move(self, y: int, x: int) -> None:
@ -118,4 +124,5 @@ class Player(FightingEntity):
d = super().save_state() d = super().save_state()
d["current_xp"] = self.current_xp d["current_xp"] = self.current_xp
d["max_xp"] = self.max_xp d["max_xp"] = self.max_xp
d["inventory"] = [item.save_state() for item in self.inventory]
return d return d

View File

@ -32,6 +32,9 @@ class TestGame(unittest.TestCase):
""" """
Save a game and reload it. Save a game and reload it.
""" """
bomb = Bomb()
self.game.map.add_entity(bomb)
bomb.hold(self.game.player)
old_state = self.game.save_state() old_state = self.game.save_state()
self.game.handle_key_pressed(KeyValues.DOWN) self.game.handle_key_pressed(KeyValues.DOWN)
@ -45,6 +48,9 @@ class TestGame(unittest.TestCase):
new_state = self.game.save_state() new_state = self.game.save_state()
self.assertEqual(old_state, new_state) self.assertEqual(old_state, new_state)
# Ensure that the bomb is loaded
self.assertTrue(self.game.player.inventory)
# Error on loading save # Error on loading save
with open(ResourceManager.get_config_path("save.json"), "w") as f: with open(ResourceManager.get_config_path("save.json"), "w") as f:
f.write("I am not a JSON file") f.write("I am not a JSON file")