基于移动和拾取物品的游戏(可能存在if-else语句问题)



我对python有点陌生,在我的课上做一个基于文本的游戏,从一个房间移动到另一个房间,有东北、东南和西部。除了第一个房间,其他房间都有玩家必须拾取的道具。移动命令为"move "direction",获取命令为"get "item"。我将房间设置在一个字典中,每个房间都有一个嵌套字典,该字典与相邻的房间和每个房间中的项目相关。这是我当前的工作代码。

def show_instructions():
print('Collect 8 items to win the game and defeat the beast')
print('Move Commands: move North, move South, move West, move East, or Exit to leave the game')
print('Pickup items: get item, ex. get swordn')
#Dictionary for rooms and Items
def main():
rooms = {
'Shed' : {'West': 'Well Room', 'item' : 'well room West of you'},
'Well Room' : {'South' : 'Sewers', 'East' : 'Shed', 'item' : 'Healing-Potion'},
'Sewers' : {'East' : 'Crawl Space','North' :'Well Room', 'item' : 'Armor'},
'Crawl Space' : {'East' : 'Cavern', 'West' : 'Sewers','item' : 'Sword'},
'Cavern' : {'South' : 'Dungeon Hall', 'West' : 'Crawl Space', 'item' : 'Shield'},
'Dungeon Hall' : {'East' : 'Hidden Room', 'West' : 'War Room', 'North' : 'Cavern', 'item' : 'Sword-Enchantment'},
'Hidden Room' : {'South' : 'Treasure Room', 'East' : 'Dungeon Hall', 'item' : 'Flame-Resistance-Potion'},
'War Room' : {'West' : 'Laboratory', 'East' : 'Dungeon Hall', 'item' : 'Armor-Enchantment'},
'Laboratory' : {'South' : 'Treasure Room', 'East' : 'War Room', 'Item' : 'Enchantment-Table'},
'Treasure Room' : {'item' : 'Dragon'}
}
#Helps with Decision branching
directions = ['North','South','East','West']
#Sets the player in the first room
currentroom = 'Shed'
inventory = []
print(show_instructions())
while currentroom != 'Exit':
def showStatus():
print('You are in the', currentroom)
print('Inventory:', inventory)
print('You see a', rooms[currentroom]['item'])
showStatus()
#Win Condition checkpoint
if currentroom == 'Treasure Room':
if len(inventory) < 8:
print('You get eaten by the Dragon')
break
else:
print('You slay the dragon and return to your boss victorious')
#input from player
c = input('What would you like to do?:n')
#exit condition
if c == 'Exit':
currentroom = 'Exit'
#split to have tokens dignify if move or get item
tokens = c.split()
if tokens[0] == 'move' or 'Move':
if tokens[1] in directions:
try:
currentroom = rooms[currentroom][tokens[1]]
except KeyError:
print('You see a Wall')
else:
print('Not a Valid Direction')
elif tokens[0] == 'get' or 'Get':
if tokens[1] == rooms[currentroom]['item']:
inventory.append(rooms[currentroom]['item'])
else:
print('Not a valid Item')
else:
print('Not a Valid Entry')
print(main())

我遇到的问题是,无论我输入get还是move,它都会启动"if令牌[0]== 'move'或'move' "线。所以键入Get只是打印'Not a Valid Direction'。谁能帮我看看我是怎么写错声明的吗?在一天结束时,我希望我的移动从一个房间到另一个房间,打印房间中的物品,能够将物品添加到库存中,并移动到下一个房间。一旦收集了8个道具,我就想在到达"宝藏室"时赢得游戏。

你的文章格式错误,所以你应该试着改正。

一般来说,你的问题是语法问题。这条线:

if tokens[0] == 'move' or 'Move':

的值总是为True,因为or==之后求值,而非空字符串的逻辑值是True修复方法如下:

if tokens[0] == 'move' or tokens[0] == 'Move':

if tokens[0] in ('move', 'Move'):

也有其他的解决方案,但以上任何一种都可以。

一旦这个问题解决了,我希望你会发现更多。尽你所能解决这些问题,并在必要时重新发布新的问题。但一定要先解决问题,并确保发布格式正确的完整代码。

最新更新