English 中文(简体)
I cannot get this Text-Based game to work for the life of me: new to coding
原标题:

I am taking a coding class and doing the ever so famous text based game, I have tried various ways to try and get this game to work and no variation will work When it comes to entering the command to change rooms; it says invalid commands. So i cannot test anything further until I am able to get that far. I had it working and then I added a more complex dictionary and everything went to poop. I dont know if i need to go back down to simpler dictionaries with easier identifyers or if i can simply find a way to make this work.

this is the full code:

areas_dic = {
     Home : { name :  Home ,  go East :  Plains ,  item :  none },
     Plains : { name :  Plains ,  go North :  Rocky Terrain ,  go East :  Fields ,  go South :    Stream ,  item :  Grains },
     Stream : { name :  Stream ,  go East :  Forest ,  item :  Water },
     Forest : { name :  Forest ,  go West :  Stream ,  item :  Firewood },
     Fields : { name :  Fields ,  go West :  Plains ,  go North :  Farmlands ,  item :  Vegetables },
     Rocky Terrain : { name :  Rocky Terrain ,  go South :  Plains ,  go East :  up the Mountain ,    item :  Medicinal Flowers },
     up the Mountain : { name :  up the Mountain ,  go West :  Rocky Terrain ,  go East :  Mountain Top ,  item :  Warmer Clothes },
     Farmlands : { name :  Farmlands ,  go South :  Fields ,  go West :  DYSENTERY ,  item :  Jerky },
     Mountain Top : { name :  Mountain Top ,  go West :  up the Mountain ,  go South :  DYSENTERY ,    item :  Milk }
    }

    print( Welcome to Old Americas )
    print( Object of the game is to collect all 7 items before falling ill )
    print( You can type go North, go South, go East, go West to move )


    current_location =  Home 
    inventory = []


    required_items = { Grains ,  Water ,  Firewood ,  Vegetables ,  Medicinal Flowers ,  Warmer Clothes ,  Milk }


    while True:
    print(f"You are in the {areas_dic[current_location][ name ]}.")

        # Display available directions
        directions = [direction for direction in areas_dic[current_location] if direction.startswith( go  )]
        print("Available directions:", ", ".join(directions))
    
        # Get player input
        command = input("Enter your command): ").strip().lower()
    
        # Process player input
   
    >  if command in directions:
    > direction = command.split()[1]
    > if direction in areas_dic[current_location]:
    > current_location = areas_dic[current_location][direction]
                item = areas_dic[current_location].get( item , None)
                if item:
                    print(f"You found {item}!")
                    inventory.append(item)
                    if item in required_items:
                        required_items.remove(item)
                        print(f"Items left to collect: { ,  .join(required_items)}")
            else:
                print("You can t go that way!")
        else:
            print("Invalid command. Try again.")
        
        # Check if player has collected all items
        if not required_items:
            print("Congratulations! You ve collected all items. Now face the villain in DYSENTERY!")
            break
        
        # Check if player has reached the final room
        if current_location ==  DYSENTERY :
            if  illness  in inventory:
                print("You have fallen ill. Game over!")
            else:
                print("You defeated the illness and survived the journey! Well done!")
            break

the block quote is where i am having the problems. or i think i am, i dont know if i am not formatting it correctly or if it needs something all together different.

问题回答

As John Gordon said in a comment, the .lower() seems to be what is messing up the code. Luckily, this should be a really easy fix.

Here is what I did to fix your problem:

#...
command = input("Enter your command): ").strip().lower()

# Checks each given direction
for direction in directions:

    # using .lower here means that no matter how we type go x it will always work.
    if command in direction.lower():
        # direction = command.split()[1]
        # ...
        
        if item:
            print(f"You found {item}!")
            inventory.append(item)

            # ...

            # We add a  break  every time we want it to stop at the other directions.
            # This isn t strictly neccessary, but it helps save some processing power, even if it
            # pretty much non-existant.
            break

        # ...

# This is added to the end so that if it goes through all of the directions
# and can t find one, it ll return the message "Invalid Command"
else:
    print("Invalid command. Try again.")

I didn t go through all the code, as in where every "break" would be placed, but hopefully you get the idea. Here s the explanation in words, instead of comments:

The for loop will check every direction. If it cant find any, it will go to the else statement at the end, and return the Invalid Command message. By adding .lower to direction and the command, we can make it so that even if you type gO EaSt or anything like that, it ll work. We can add break statements whenever we want the program to return to the "command =..." line.





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签