-1

Working on a project for an intro to python scripting course. The project is to build a game starting with some basic code they provide to create an adventure that takes you through several rooms, collecting items along the way. I've been able to get most of the requirements working but after adding the inventory system to the game, its become pretty slow to process and is also creating an issue with how the game progresses. I have no doubt that code is inefficient and could be either reorganized or just use different looping.

Before getting the inventory system operating as required, it would take a user input for direction, tell you if it was the correct room and if there was an item in the room, you would type a move, then move to the next room if it was correct. Now, when the game starts, it shows you in correct room with no item (As expected), you type a move and it is now very slow to process the next move. Then it shows the item and prompts before showing you in the room with your inventory, where it should be showing you in the room, that there is an item, and what your inventory is.

If anyone could help point out what I'm doing wrong, I would greatly appreciate it.

import time
# A dictionary for the Server room text game
# The dictionary links a room to other rooms.
rooms = {
        'IT Office': {'South': 'Corporate Office'}, # First Room
        'Corporate Office': {'North': 'IT Office', 'South': 'Cafeteria', 'East': 'Supply Closet', 'item': 'fix it guide'},
        'Supply Closet': {'West': 'Corporate Office', 'item': 'plumbers tape'},
        'Cafeteria': {'North': 'Corporate Office', 'West': 'Break Room', 'South': 'Maintenance Facility', 'item': 'poncho'},
        'Break Room': {'East': 'Cafeteria', 'item': 'rain boots'},
        'Maintenance Facility': {'North': 'Cafeteria', 'East': 'Equipment Shed', 'item': 'pipe wrench'},
        'Equipment Shed': {'West': 'Maintenance Facility', 'North': 'Server Room', 'item': 'section of pipe'},
        'Server Room': {'South': 'Equipment Shed'} #Last Room
}

#defining the game instructions
def introduction():
    print('')
    print('********** Server Room Text Adventure Game **********\n')
    time.sleep(1.0)
    print('*****************************************************')
    print('\nThere are 8 rooms to move between and 6 items to pick up\n')
    print('that you will require to complete your adventure.\n')
    print('Directions: You can go North, South, East, or West\n')
    print('to navigate between rooms. If the room has an item\n')
    print('it will be picked up and added to your inventory.\n')
    print('You can also type exit to leave the game. Good Luck!\n')
    print('*****************************************************\n\n')
    time.sleep(2.0)

# Defining player status, prints
def player_status():
    print('=========================================')
    print('\nYou are currently in the {}'.format(currentRoom))
    print('\nYour current inventory: {}'.format(inventory))
    #print('You see a {}'.format(currentItem))
    print('\n=========================================')
    print('\n')

# Inventory list to hold inventory as it's added in each room
inventory = []

user_item = ''
# defining Inventory carried to add to inventory list
def game(item):
    #user_item = input('')

    if item in inventory:  # use in operator to check membership
        print("you already have got this")
        print(" ".join(inventory))

    elif item not in inventory:
        print('You see a', item)
        print('Would you like to pick it up? \n')
        user_item = input('')
        if user_item == 'Y':
            print('item has been added\n')
            inventory.append(item)
        else:
            print('You leave the item behind.')
    #else:
        #print("You see a", item)
        #print("and you pick it up, its been added to inventory")
        #inventory.append(item)
        #print(" ".join(inventory))


# Current Room, starts off in IT Office
currentRoom = 'IT Office'

# Players Move
player_move = ''

# Calling the Introduction function
introduction()

# While Loop for moving between rooms
while True:
    player_status()

    player_move = input('Enter a move: \n')

    if player_move == 'Exit':
        print('Thanks for playing.')
        # break statement for exiting
        break

    if player_move in rooms[currentRoom]:
        currentRoom = rooms[currentRoom][player_move]

        addItem = input(' \n')

        if 'item' in rooms[currentRoom]:
            game(rooms[currentRoom]['item'])

        #if/else statements with break statement for final room/finishing the game
        if currentRoom == 'Server Room':
            if len(inventory) == 6:
                print('\n***********************     Congratulations!     ***********************')
                time.sleep(1.0)
                print('\n************************************************************************')
                print('\nYou have made it to the Server Room with all of the items to ')
                print('fix the burst pipe. You used the items you collected to repair')
                print('the pipe, and Saved the Data! You are a Hero to your company!\n')
                print('*************************************************************************\n')
                time.sleep(2.0)
                print('^^^^^^^^^^^^^^^^^^^^^^^^^^ Thanks for playing! ^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n')
                break

            else:
                print('\n################## You Failed! #####################')
                time.sleep(1.0)
                print('\n####################################################')
                print('\nYou are missing items needed to fix the pipe')
                print('& the Server Room has flooded. All of your')
                print('companies data is gone. Time to polish your resume.')
                print('\n####################################################\n')
                print('@@@@@@@@@@@@@@@@@@@ Please play again @@@@@@@@@@@@@@@@')
                break

    # else statement for input validation/invalid move
    else:
        print('\nYou walk in to a wall, try again.\n')
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    You use ```time.sleep``` a lot, maybe it enters the conditional in the place it shouldn't. – Yulian Feb 20 '21 at 20:15
  • 1
    You have an additional input here: `addItem = input(' \n')` that you at some time seem to have moved into the `game` function (you probably want to call that function something like `pick_up_item` instead to describe what it _actually does_ as well). Because of that additional `input`, your game will appear to lag until you press an additional enter key. – MatsLindh Feb 20 '21 at 20:18
  • Please provide the expected [MRE - Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). Show where the intermediate results deviate from the ones you expect. We should be able to paste a single block of your code into file, run it, and reproduce your problem. This also lets us test any suggestions in your context. – Prune Feb 20 '21 at 20:20
  • As @MatsLindh says, you have an input for `addItem` that has no prompt string, so when you play the game, you don't know what you're being asked to enter. You should add a prompt string saying "what would you like to pick up?" or something like that. You don't do anything right now with that `addItem` value. Maybe you should comment out that line and see how your game performs without that pause for input. - you aren't doing anything in your game that takes any time other than the calls to `sleep()`. If you think your game is going slow, it's either waiting for input or sleeping. – CryptoFool Feb 20 '21 at 20:22
  • This post appears to be a full code dump, rather than your MRE. We also expect that you will trace the problem and print useful values. Where are you confused about how they got to those values? Your posted program hangs waiting for input. Do not expect us to provide test data: simply replace your `input` with a test case that elicits the problem. "slow to process" and "creating an issue" are vague statements, not a problem specification. – Prune Feb 20 '21 at 20:22
  • Nothing slow here. Just remove/comment this useless line: ##addItem = input(' \n') – Malo Feb 20 '21 at 20:54
  • See [Why is “Can someone help me?” not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question) – martineau Feb 20 '21 at 21:36
  • First, find out where your code is spending most of its time: [How can you profile a Python script?](https://stackoverflow.com/questions/582336/how-can-you-profile-a-python-script) Then try to speed up or eliminate those parts of your code. – martineau Feb 20 '21 at 21:40
  • Thanks for the feedback, MatsLindh had it, removing the additional addItem = input was what fixed the issue. The sleeps that are added were just for the presentation of the game when the user loads it. I apologize for the poor explanation, I'm very much a newbie and this class has been challenging to me. – frestylmotox01 Feb 20 '21 at 21:56

1 Answers1

1

First two suggestions:

I'd highly recommend when you have questions like this, step through your code in a debugger. I suspect had you done that you would have seen the issue fairly quickly, as you'd step into the problem line of code and realize what's going on. Or at the least, you could save others the questions, and as suggested produce a smaller MRE that produces the problem.

Also, in cases like this, where you do have code that can slow things down and not change the outcome, it can be handy to "stub it out". For instance, if you replace all of your calls to time.sleep with calls to a function like this:

REALLY_SLEEP = False
def sleep(value):
    if REALLY_SLEEP:
        time.sleep(value)
    else:
        import inspect
        print(f"**** Sleep called for {value}s at {inspect.stack()[1].lineno} ****")

You can then quickly run through your program as you're testing and developing it, and set the REALLY_SLEEP flag to True when you're ready for others to play it.

All of that said: You're not taking a long time when you do move to another room, you're taking forever:

    if player_move in rooms[currentRoom]:
        currentRoom = rooms[currentRoom][player_move]

        addItem = input(' \n')

This code checks to see if the user typed in a valid move, and if they did, moves to the new room, and waits for user input without anything the user can detect as a prompt for input. addItem isn't used, so I assume it's random code from an early iteration that was forgotten about. Get rid of that line and things will work.

Which loops back to my opening suggestion: Learn to use a debugger, either in an IDE or not, and stepping through code will immediately show what it's doing.

Anon Coward
  • 9,784
  • 3
  • 26
  • 37