Help us with our game, error

Question:


Repl link:


code snippet

error:

Traceback (most recent call last):
  File "main.py", line 584, in <module>
    raise e
  File "main.py", line 565, in <module>
    battleOld()
  File "main.py", line 349, in battleOld
    print(f'You attack the {bright}{colored(enemy_pokemon, rarity, attrs=["blink"])}{normal} with {bright}{stats[your_pokemon]["abilities"]}{normal} for {red}{bright}{stats[your_pokemon]["damage"]}{normal}{white} damage!') ; enemy_stats["health"]-= stats[your_pokemon]["damage"]
KeyError: 'invalid'

x

def battleOld():
  gen_pokemon_cnt = 0
  if all(slot == '' for slot in pokemon_slot):
    print('You do not have any Pokemon in your slots!')
  else:
    while True:
      try:
        if not any(slot != '' for slot in pokemon_slot):
          print('All your Pokemon have fainted!')
          break

        # Choose enemy pokemon
        if gen_pokemon_cnt == 0:
          
          enemy_tier = random.randint(1, 100)
          if enemy_tier == 1:
            enemy_pokemon = random.choice(['Mew', 'Mewtwo'])
            rarity = 'yellow'
          elif 2 <= enemy_tier <= 14:
            enemy_pokemon = random.choice(pokemon_list + ['Lapras', 'Dragonite'])
            rarity = 'blue'
          elif 15 <= enemy_tier <= 49:
            enemy_pokemon = random.choice(pokemon_list)
            rarity = 'green'
          else:
            enemy_pokemon = random.choice(['Rattata', 'Spinarak', 'Pidgey', 'Zigzagoon'])
            rarity = 'white'
          # Retrieve the stats for the enemy Pokemon from the stats dictionary
          enemy_stats = stats.get(enemy_pokemon, {"abilities": "Tackle", "special_ability": {}, "damage": 40, "enemy_pokemon_paralyze": False, "paralyze_chance": 0,'health': 120});original_hp_enemy = enemy_stats['health'];
          # Clear the console window
          clear()
          # Initialize the player's choice to an invalid value
          choice = ''
          gen_pokemon_cnt = 0
          # Enter the battle turn loop

        # Select your pokemon
        your_pokemon = 'invalid'  # Initialize to empty string  
        if gen_pokemon_cnt == 0:
          
          while your_pokemon not in pokemon_slot:
            
            print(f'{bright}{white}Please select your Pokémon:')
            for i, slot in enumerate(pokemon_slot):
              print(f'[{i+1}] {slot}')
            choice = input()
            if not choice.isdigit():
              continue
            index = int(choice) - 1
            if index < 0 or index >= len(pokemon_slot):
              continue
            your_pokemon = pokemon_slot[index]
            original_hp_you = stats[your_pokemon]['health']
            clear()
            
          # Your turn
        gen_pokemon_cnt = 1
        while True:
          clear()
          print(f'{bright}{white}What do you want to do?')
          print(f'[{blue}1{white}] {red}Attack{white}')
          print(f'[{blue}2{white}] Use {purple}Potion{white}')
          print(f'[{blue}3{white}] Catch Pokémon')
          print(f'[{blue}4{white}] Run Away')
          choice = input()

          if choice == '1':
            print(f'You attack the {bright}{colored(enemy_pokemon, rarity, attrs=["blink"])}{normal} with {bright}{stats[your_pokemon]["abilities"]}{normal} for {red}{bright}{stats[your_pokemon]["damage"]}{normal}{white} damage!') ; enemy_stats["health"]-= stats[your_pokemon]["damage"]
            break
          elif choice == '2':
            print(f'Using a {purple}{bright}potion{normal}{white} to heal your Pokémon...')
            time.sleep(3)
            #work on later. 
            break
          elif choice == '3':
            print('Throwing a Pokéball!')
            sleep(2)
            if rarity == 'yellow' or rarity == 'blue':
              print(f"Congratulations! You caught a wild {bright}{colored(enemy_pokemon, rarity)}{normal}!");gen_pokemon_cnt = 0
              sleep(2)
              print(f"{bright}{colored(enemy_pokemon, rarity)}{normal} was added to your {red}{bright}Pokédex{normal}{white}!")
              break
            else:
              print(f"{bright}{colored(enemy_pokemon, rarity)}{normal} broke free!")
              sleep(2)
              enemy_choice = random.choice(["1", "2"])
              if enemy_choice == "1":
                  print(f"The wild {bright}{colored(enemy_pokemon, rarity)}{normal} attacked you with {bright}{enemy_stats['abilities']}{normal}!")
              else:
                  print(f"The wild {bright}{colored(enemy_pokemon, rarity)}{normal} used {bright}{list(enemy_stats['special_ability'].keys())[0]}{normal} on you!")
                  # activate special ability

          elif choice == '4':
            print('You ran away from the battle!')
            enter_to_continue()
            clear()
            return
          else:
            print("Invalid option. Please try again.")
            sleep(2)
            clear()
            continue
        
        # Enemy turn
        hp_cur = int(enemy_stats['health'])
        if hp_cur <=0:
          enemy_stats['health'] = original_hp_enemy
          print('You have defeated the pokemon.')
          enter_to_continue()
          clear()
          break
          
        print(f'{bright}{white}The {colored(enemy_pokemon, rarity, attrs = ["blink"])} {normal}attacks with {bright}{enemy_stats["abilities"]}{normal}');
        sleep(1)  # Delay for dramatic effect
        print(f'{white}The {bright}{colored(enemy_pokemon, rarity, attrs = ["blink"])}{normal} dealt {bright}{red}{enemy_stats["damage"]}{normal}{white} damage!');stats[your_pokemon]['health'] -= enemy_stats['damage']
        sleep(3)
        clear()
        hp_cur = int(stats[your_pokemon]['health'])
        if stats[your_pokemon]['health'] <=0:
          stats[your_pokemon]['health'] = original_hp_you
          print('You have been defeated.')
          enter_to_continue()
          clear()
          gen_pokemon_cnt = 0
          break
          
      except KeyboardInterrupt:
        print('You ended the battle!')
        enter_to_continue()
        clear()
        break

Help us fix the code, please.

From what I see you are trying to access a dictionary key that does not exist.

Right here:

print(f'You attack the {bright}{colored(enemy_pokemon, rarity, attrs=["blink"])}{normal} with {bright}{stats[your_pokemon]["abilities"]}{normal} for {red}{bright}{stats[your_pokemon]["damage"]}{normal}{white} damage!') ; enemy_stats["health"]-= stats[your_pokemon]["damage"]

It seems that if the player doens’t make a valid choice the key here will be invalid (the key being your_pokemon) which will generate the error.

I suggest a nested loop, so the player can’t move on until they’ve selected a valid Pokémon.

You can read more about nested loops here:

By adapating from your code it would be something like this:

while True:  # put a loop to make sure we get a valid pokemon
  print(f'{bright}{white}Please select your Pokémon:')
  for i, slot in enumerate(pokemon_slot):
    print(f'[{i+1}] {slot}')
  choice = input()
  if not choice.isdigit():
    continue
  index = int(choice) - 1
  if index < 0 or index >= len(pokemon_slot):
    continue
  your_pokemon = pokemon_slot[index]
  if your_pokemon == '':  # check if it's a empty slot
    print('That slot is empty, choose a different one.')
    continue
  original_hp_you = stats[your_pokemon]['health']
  clear()
  break  # if we get to here, a valid pokemon was chosen, so we break the loop

2 Likes