简体   繁体   中英

Python text based game. display items, get items

I have got the movement down but can not get it to display the item of the room when you move into a room. I also can not get it to pick up an item that is in a room. I do not want direct code if it is possible I want to learn how to do it. I am using a dictionary for the rooms and items and I have tried doing rooms[currentRoom['Item']] and rooms[currentRoom]['Item'} both give me a key error. I also need to know how to change the dictionary from go South to just South but you still have to use go South to move anywhere. I could not figure it out either. This is for my school project due on Sunday and I have worked on it for weeks and researched for an answer and can not find one anywhere. I have tried many things but none have worked the try and except method is the only one I could get to work for the movement. And once you get to the mammoth fields I want to be able to fight the boss and check if you have all the items and if not than you die and game over but if you have all the items you fight the boss and win.

Here is my code so far:

def showInstructions():
 # print the main menu instructions
 print('Neanderthal Text Adventure game')
 print('Collect all 7 Items and defeat the mammoth boss at the end to win.')
 print('Movement commands: go South, go North, go East, go West')
 print("To add item to inventory: get 'item name'")
 print('To fight the boss type: "Fight Boss"')


def player_stat(currentRoom, Inventory, rooms):
 print('   -------------------------------------------')
 print('You are in the {}'.format(currentRoom))
 print('Inventory:', Inventory)
 print('   -------------------------------------------')


currentRoom = ''
# define the player inventory which starts empty.
Inventory = {}


def main():
 rooms = {
     'Grasslands': {'go South': 'Caves', 'go North': 'Beach', 'go East': 'Icy Forest', 'go West': 'Forest'},
     'Caves': {'go North': 'Grasslands', 'go West': 'Rocky Plateau', 'Item': 'Cave Moss Helmet'},
     'Beach': {'go South': 'Grasslands', 'go East': 'Camp', 'go West': 'Mountains', 'Item': 'Seashell Boots'},
     'Icy Forest': {'go North': 'Camp', 'go East': 'Mammoth Fields', 'go West': 'Grasslands', 'Item': 'Icy Shield'},
     'Forest': {'go North': 'Mountains', 'go East': 'Grasslands', 'go South': 'Rocky Plateau',
               'Item': 'Leafy Chestplate'},
     'Mountains': {'go South': 'Forest', 'go East': 'Beach', 'Item': 'Rock Club'},
     'Rocky Plateau': {'go North': 'Forest', 'go East': 'Caves', 'Item': 'Rocky Leggings'},
     'Camp': {'go West': 'Beach', 'go South': 'Icy Forest', 'Item': 'Fire Stick'},
     'Mammoth Fields': {'go West': 'Icy Forest', 'Fight Boss': 'Mammoth'}
     }
    currentRoom = 'Grasslands'

# Show player the game instructions
showInstructions()

# loop forever
while True:

    player_stat(currentRoom, Inventory, rooms)
    playerMove = str(input('Enter your move: '))
    if playerMove in ['Exit', 'exit']:
        currentRoom = 'Exit'
        print('Play again soon!')
        exit()
    if playerMove is not str():
        print('Try typing words.')
    if playerMove == str('get ' + rooms[currentRoom]['Item']):
        if rooms[currentRoom]['Item'] and Inventory:
            print('You already have this item in your inventory!')
        else:
            Inventory.append(rooms[currentRoom]['Item'])

    try:
        currentRoom = rooms[currentRoom][playerMove]
    except KeyError:
        print("invalid move")
        continue


 main()

Your biggest issue is that not all of your rooms values contain an 'Item' key. That makes rooms[currentRoom]['Item'] raise an error when you try to use it. Since you start in a room with no item (the Grasslands), you're likely getting errors immediately.

There are a few ways you could work around this. You could add a dummy value (such as None ) to the dictionary to indicate when there is no item present. Or you could use the dict.get method to get a default value (like None ) when you try to look up a nonexistent key.

I'd try something like this:

if playerMove in ['Exit', 'exit']:     # this part is unchanged
    currentRoom = 'Exit'
    print('Play again soon!')
    exit()
# note, the comparison to `str()` was not useful, so I've removed it from here

item = rooms[currentRoom].get('Item')  # get the item present, or None if there isn't one
if item is not None and playerMove == 'get ' + item:
    if item in Inventory:              # fixed typo: and -> in
        print('You already have this item in your inventory!')
    else:
        Inventory.append(item)

# ...

Note that since you are append ing to the inventory, you probably need to initialize it to an empty list, not the empty dictionary you're currently using. A set could also make sense, since you frequently check it for membership (and that's more efficient in a set than in a list).

I'd also note that you probably will need to update your game's output to describe the items that can be picked up with get . Currently you don't have anything to do that, and so the player won't have any way of knowing what there is to pick up. You could add this to player_stat , or maybe add an additional command like "look" to get a description of the contents of the room (and maybe the exits).

I have this same project. What i did was for the status i added an if statement that if the location has an item then it will display the item with the status by using .join so it would look something like this.

    print('-' * 20)
    print('You are in the {}'.format(location['name']))
    print('Your current inventory: {}\n'.format(inventory))
    if location['item']:
        print('Item in room: {}'.format(', '.join(location['item'])))
        print('')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM