Can anyone help with my saving system?

Question:
Can anyone help me with my pickle saving system
Repl link:
aaronduan123 (Later Allig4tor) - Replit
Just a little bit of my code:

playername = os.environ["REPL_OWNER"]

def load_player_data(playername):
  try:
      with open(f"{playername}_player_data.pkl", "rb") as file:
          data = pickle.load(file)
          inventory = data.get("inventory", [])
          total_coins = data.get("coins", 0)
          badges = data.get("badges", [])
          level = data.get("level", 1)
          xp = data.get("xp", 0)

      print(f"Loading data for {playername}: {inventory}, {total_coins}, {badges}, {level}, {xp}")
      return data, inventory, total_coins, badges, level, xp
  except FileNotFoundError:
      return {}, [], 0, [], 1, 0

def save_player_data(playername, inventory, total_coins, badges, level, xp):
  data = {"coins": total_coins, "inventory": inventory, "badges": badges, "level": level, "xp": xp}
  with open(f"{playername}_player_data.pkl", "wb") as file:
      pickle.dump(data, file)

  print(f"Data saved for {playername}")

class Player:
  def __init__(self, name, level=1, xp=0, max_xp=100, health=100, credits=0, max_level=100, inventory=None, badge=None):
      self.name = name
      self.level = level
      self.xp = xp
      self.max_xp = max_xp
      self.health = health
      self.credits = credits
      self.max_level = max_level
      self.inventory = inventory or []
      self.badge = badge or []

  def is_alive(self):
      return self.health > 0

  def take_damage(self, damage):
      self.health -= damage

  def attack_enemy(self):
      return random.randint(0, 25)

  def gain_xp(self, amount):
      self.xp += amount
      if self.xp >= self.max_xp:
          self.level_up()


  def level_up(self):
    if self.xp >= self.max_xp:
        if self.level < self.max_level:
            self.level += 1
            self.health += 50
            self.xp = 0
            self.max_xp += 20
            print(f"{self.name}, congratulations! You leveled up to Level {self.level}.")
        else:
            print(f"{self.name}, you have reached the maximum level.")


  def display_stats(self):
      print("\nPlayer Stats:")
      print(f"Name: {self.name}")
      print(f"Level: {self.level}")
      print(f"XP: {self.xp}/{self.max_xp}")
      print(f"Health: {self.health}")
      print(f"Credits: {self.credits}")
      if self.badge:
          print(f"Badge: {self.badge}")
      else:
          print("Badge: None")
      if self.inventory:
          print(f"Inventory: {self.inventory}")
      else:
          print("Inventory: Empty")


  @classmethod
  def load_player(cls, name):
    try:
        with open(f"{name}_player_data.pkl", "rb") as file:
            data = pickle.load(file)
            player = cls(name)
            player.__dict__.update(data)
            return player
    except FileNotFoundError:
        return cls(name)


  def save_player(self):
    with open(f"{self.name}_player_data.pkl", "wb") as file:
        pickle.dump(self.__dict__, file)
player = Player
#SAVING STUFF



player = Player(playername)  # Create an instance of the Player class 



here is some more if u need:

#NPC
class Mob:
  def __init__(self, name, health, attack):
      self.name = name
      self.health = health
      self.attack = attack

  def is_alive(self):
      return self.health > 0

  def take_damage(self, damage):
      self.health -= damage

  def attack_player(self):
      return random.randint(1, self.attack)


#COMBAT
class Combat:
  @staticmethod
  def start(player, enemy):
      clear()
      print(f"\nYou explore and found a {bold}{darkgrey}cave{reset}. In this {bold}{darkgrey}cave{reset} you spotted a{red}{bold}{enemy.name}{reset}!")
      while player.is_alive() and enemy.is_alive():
          print(f"\n{player.name}'s Health: {player.health} | {enemy.name}'s Health: {enemy.health}")
          print("Choose your move:")
          print(f"1.{orange} Attack")
          print(f"2.{blue} Defend{reset}")

          move_choice = input("Enter your move (1/2): ")

          if move_choice == '1':
              player_damage = player.attack_enemy()
              enemy_damage = enemy.attack_player()

              print(f"\nYou dealt {player_damage} damage to {enemy.name}.")
              enemy.take_damage(player_damage)

              print(f"{enemy.name} dealt {enemy_damage} damage to you.")
              player.take_damage(enemy_damage)

          elif move_choice == '2':
              print(f"You chose to defend. You take reduced damage this turn.")
              enemy_damage = enemy.attack_player() // 2
              player.take_damage(enemy_damage)

          else:
              print("Invalid move. You stumble and take extra damage.")
              player.take_damage(enemy.attack_player())

      if player.is_alive():
          print(f"\nCongratulations! You defeated the {enemy.name}!")
          player.gain_xp(50)
          player.credits += 200
          player.save_player()
          
      else:
          print("Game Over. You were defeated by the enemy.")
          player.save_player()
#GAME LOOP 
while True:
  write3(f"""
            {bold}Options:             {reset}
  1. {red}Explore ⚔ .{reset}
  2. {orange}Check stats.{reset}
  3. {yellow}Mine(comming soon).{reset}
  4. {green}Sell(comming soon).{reset}
  5. {blue}Shop(comming soon).{reset}
  6. {cyan}Badges!{reset}
  7. {purple}Save and exit.{reset}
  
  """)
  choice = input(f"{purple}Enter your choice: {reset}")
  
  if choice == "1":
    clear()
    if random.choice([True, False]):
      mob = Mob("Goblin", health=30, attack=8)
      Combat.start(player, mob)
    elif random.choice([True, False, False]):
      write2("You found a chest!")

What kind of help you need?

You want to make your code more clean? Correct bugs? What project do you need help with and try to specify which help is needed

2 Likes

when check stats it won’t show the correct stats

There is no code regarding checking stats (No if block for choice 2)
Have you tried debugging the Player object creation, deserialization and serialization?

1 Like

thanks I will try that