'Py Script Question - subtlety needed (student learning here) creating simple game program and my statement needs some work
This is for a intro to Python class. Typical exercise, move through the rooms, get an item (add to an inventory list), and win the game. I've gotten the move part down, it's the get/add to list part that is driving me up a wall.
My code to follow in its entirety but this ELIF section is what I need some guidance on.
below on execution gets the "invalid move" when trying to get the 'item' from the room. I get that my elif statement is probably not the best, and that my join is the problem, but variations on this theme aren't helping. Where did I go wrong?
Excerpt code with
elif len(move) == 4 and move[0] == 'Get' and s.join(move[1:3]) in rooms[current_room]['item']:
print('You pick up the {}'.format(rooms[current_room]['item']))
get_item(current_room, move, rooms, inventory)
Full code
def main_menu():
print('\nThe Castle Thief Game')
print('Collect all 6 treasures and bribe the guard if you encounter him to get out…better have all 6 though!')
print('Move Commands: go South, go North, go East, go West')
print('Add Item to Inventory: get "item name"\n')
def move_between_rooms(current_room, move, rooms):
current_room = rooms[current_room][move]
return current_room
def get_item(current_room, rooms, inventory):
inventory.append(rooms[current_room]['item'])
del rooms[current_room]['item']
def main():
rooms = {'Main Castle Hall': {'South': 'Princess Sitting Room', 'North': 'Royal Alchemy Lab', 'East': 'Kings Sitting Room', 'West': 'Guard Room'},
'Kings Sitting Room': {'West': 'Main Castle Hall', 'North': 'Kings Bedroom', 'item': 'Royal Sword'},
'Kings Bedroom': {'South': 'Kings Sitting Room', 'item': 'Kings Crown'},
'Princess Sitting Room': {'North': 'Main Castle Hall', 'East': 'Princess Bedroom', 'item': 'Magic Bow'},
'Princess Bedroom': {'West': 'Princess Sitting Room', 'item': 'Princess Tiara'},
'Royal Alchemy Lab': {'South': 'Main Castle Hall', 'East': 'Royal Library', 'item': 'Potion of Invisibility'},
'Royal Library': {'West': 'Royal Alchemy Lab', 'item': 'Grimoire'},
'Guard Room': ''
}
s = ' '
inventory = []
current_room = 'Main Castle Hall'
main_menu()
while True:
if current_room == 'Guard Room':
if len(inventory) == 6:
print('Bribe time! The guard draws his sword slowly...clearly not wanting to...')
print('You nonchalantly hand the guard a treasure...')
print('...the guard relaxes and smiles, then goes on his way. >phew!<')
print('Congratulations you have bribed the guard and live to see another day!')
print('That is all folks, you win! Play again some time!')
break
else:
print('The guard looks expectantly at you for a bribe..."')
print('Oh crud, you realize you do not have anything to give! With a disappointed look and a shrug...')
print('**STAB**...the guard runs you through with his sword! ')
print('The last thing you see and hear is the guard muttering about gotta pay if you wanna play.')
print('You have died, please try again...and this time get all the treasures first!!!')
break
print('You are in the ' + current_room)
print(inventory)
if current_room != 'Guard Room' and 'item' in rooms[current_room].keys():
print('You see the {}'.format(rooms[current_room]['item']))
print('------------------------------')
move: list[str] = input('Enter your move: ').title().split()
if len(move) >= 2 and move[1] in rooms[current_room].keys():
current_room = move_between_rooms(current_room, move[1], rooms)
continue
elif len(move) == 4 and move[0] == 'Get' and s.join(move[1:3]) in rooms[current_room]['item']:
print('You pick up the {}'.format(rooms[current_room]['item']))
get_item(current_room, move, rooms, inventory)
else:
print('invalid move, please try again')
continue
main()
I tried modifying my elif statement but to no avail so far. I can get it to error out, with an index out of range but I feel like I am missing the forest for the trees. I am expecting to "get" the item from the current_room I am in and adding it to my inventory[] empty list. the goal is to get the inventory full with all 6 'items' and when I encounter the guard in my code I can win the game. So far, been unsuccessful modifying the elif statement to correctly work.
Solution 1:[1]
Rather than guessing what might have been selected based on how many words are available, I would advise defining actions:
actions = ['go', 'get', 'check', 'quit'] # for example
and then just splitting the first element off the input with maxsplit and checking against this for initial validity:
while True:
move = input('Enter your move: ').lower().split(sep=None, maxsplit=1)
if len(move) > 0 and move[0] in actions:
break
print('Valid actions are: ' + ', '.join(actions))
act = actions.index(move[0])
then the index of the action word lets you choose the next code branch with confidence, and move[1] may be available (or not) as the subject of the action. Informative statements on what doors/items are available in appropriate cases would be easier to produce.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Joffan |
