基于文本的游戏太慢

时间:2021-02-20 20:12:50

标签: python

正在为 Python 脚本课程介绍项目工作。该项目是从他们提供的一些基本代码开始构建游戏,以创建一个冒险,带您穿越多个房间,沿途收集物品。我已经能够满足大部分要求,但是在将库存系统添加到游戏后,它的处理变得非常缓慢,并且还对游戏的进行方式造成了问题。我毫不怀疑代码效率低下,可以重新组织或只是使用不同的循环。

在让库存系统按要求运行之前,需要用户输入方向,告诉您它是否是正确的房间,如果房间中有物品,您将输入移动,然后移动到下一个房间,如果它是正确的。现在,当游戏开始时,它会向您显示没有物品的正确房间(正如预期的那样),您输入一个移动,现在处理下一步移动非常。然后它会显示该物品并提示您在房间中显示您的库存,它应该向您展示房间中的哪个位置,有一个项目,以及您的库存是什么。

如果有人能帮助指出我做错了什么,我将不胜感激。

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')

1 个答案:

答案 0 :(得分:1)

前两个建议:

我强烈建议您在遇到此类问题时,在调试器中逐步调试您的代码。我怀疑如果你这样做了,你会很快看到问题,因为你会进入问题代码行并意识到发生了什么。或者至少,您可以将问题保存给其他人,并按照建议生成产生问题的较小 MRE。

此外,在这种情况下,如果您的代码确实会减慢速度而不改变结果,那么“存根”可能会很方便。例如,如果您将所有对 time.sleep 的调用替换为对如下函数的调用:

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} ****")

然后,您可以在测试和开发程序时快速运行程序,并在准备好供其他人使用时将 REALLY_SLEEP 标志设置为 True。

所有这一切都说:当你搬到另一个房间时,你不会花很长时间,你会花很长时间:

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

        addItem = input(' \n')

此代码检查用户是否输入了有效的移动,如果输入了,则移动到新房间,并等待用户输入,而没有任何用户可以检测到的输入提示。 addItem 未使用,因此我假设它是早期迭代中被遗忘的随机代码。摆脱那条线,一切都会好起来的。

这又回到了我的开篇建议:学习在 IDE 中或不在 IDE 中使用调试器,单步执行代码将立即显示它在做什么。

相关问题