让用户输入匹配特定的条件(Python)

  • 本文关键字:条件 Python 用户 python
  • 更新时间 :
  • 英文 :


我目前正在为一个学校项目制作一款基于文本的游戏。我唯一的问题是,当用户输入不包括"Take"和[项目名称]时,我无法让我的程序打印"无效输入"。因此,只要用户输入"Take",该物品就会被添加到库存中。

import sys
def start_menu():
# Print start menu and commands
print('<>' * 50) # Print lines to separate text
title = (r"""  
╔═╗┬─┐┌─┐┌─┐┌┬┐  ╔═╗┬ ┬┬─┐┌─┐┌┬┐┬┌┬┐  ┌─┐┌─┐  ╔╦╗┌─┐┌─┐┬─┐┌─┐┌─┐┌┐┌
║ ╦├┬┘├┤ ├─┤ │   ╠═╝└┬┘├┬┘├─┤││││ ││  │ │├┤   ║║║├┤ ├┤ ├┬┘├┤ ├┤ │││
╚═╝┴└─└─┘┴ ┴ ┴   ╩   ┴ ┴└─┴ ┴┴ ┴┴─┴┘  └─┘└    ╩ ╩└─┘└─┘┴└─└─┘└─┘┘└┘
""")
print(title)
print('<>' * 50 )  # Print lines to separate text
print('You are a Spy visiting the Great Pyramid of Meereen. You must make your way from the top of then'
'Pyramid to the Dragon Pit. Collect all of the items along the way to help defeat the two Dragons.n'
'If you are successful you will put an end to Queen Daenerys reign and save the Seven Kingdoms.n'
'nHappy Adventuring!')
print('<>' * 50)
print('Input move: North, South, East or West')
print('Input "Take [item name]" to add item to inventory')
print('Input "Exit" to quit game')
print('<>' * 50)
start_menu()
# Dictionary of rooms and items
rooms = {
'Terrace': {'East': 'Daenerys Chambers'},
'Daenerys Chambers': {'West': 'Terrace', 'East': 'Barristan's Chambers', 'South': 'Royal Chambers',
'item': 'Dragon Necklace'},
'Barristan's Chambers': {'West': 'Daenerys Chambers', 'item': 'Barristan's Sword'},
'Royal Chambers': {'North': 'Daenerys Chambers', 'South': 'Torture Cells',
'West': 'Audience Chamber', 'East': 'Stables', 'item': 'Milk of the Poppy'},
'Audience Chamber': {'East': 'Royal Chambers', 'item': 'Torch'},
'Stables': {'West': 'Royal Chambers', 'item': 'Health Potion'},
'Torture Cells': {'North': 'Royal Chambers', 'East': 'Dragon Pit', 'item': 'Magic Potion'},
'Dragon Pit': {'West': 'Torture Cells', 'Item': 'Dragons'}
}
def gameplay_loop():
move_direction = ['North', 'South', 'East', 'West']
inventory = []
current_room = 'Terrace'
# Gameplay loop
while True:
# Display Inventory
print('Inventory', inventory, 'n')
# Shows current location and item
if current_room == 'Terrace':
print('You are on the {}.n'.format(current_room))
if current_room == 'Daenerys Chambers' or current_room == 'Barristan's Chambers':
print('You are in {}.'.format(current_room))
if item not in inventory:
print('Item:', item, 'n')
else:
print('You have collected all of the items in this room.n')
elif current_room != 'Terrace':
print('You are in the {}.'.format(current_room))
if current_room == 'Torture Cells':
print('A sign reads: "Beware of Dragon Pit: East"')
if item not in inventory:
print('Item:', item, 'n')
else:
print('You have collected all of the items in this room.n')
# Display user input
user_input = input('Enter your move:' + 'n' + '> ')  # Movement control
print('')  # Space for visual formatting
user_input = user_input.capitalize()  # Capitalize user input to match dictionary
print('<>' * 50)
if user_input in move_direction:
user_input = user_input
if user_input in rooms[current_room].keys():
current_room = rooms[current_room][user_input]
print(current_room)
print('<>' * 50)
else:
# for invalid movement
print('You can't go there!')
print('<>' * 50)
# Check for exit command
elif user_input == 'Exit':
print('Thank you for playing!')
print('<>' * 50)
break
# invalid command
elif 'Take' not in user_input:
print('Invalid inputn')
if current_room != 'Terrace' and current_room != 'Dragon Pit':
item = rooms[current_room]['item']
# Update inventory
if 'Take' in user_input and current_room != 'Terrace' and item not in inventory:
inventory.append(item)
print('You found:', item)
print('<>' * 50)
if current_room == 'Terrace' and 'Take' in user_input:
print('There is no item here!')
print('<>' * 50)
# Game over
if len(inventory) == 6 and current_room == 'Dragon Pit':
print('nYou have defeated the Dragons and saved the Seven Kingdoms!')
print('Thanks for playing!')
restart_game()
elif len(inventory) < 6 and current_room == 'Dragon Pit':
print('nYou died.')
print('Collect all six items before facing the Dragons...')
restart_game()

def restart_game():
# Restart or exit game
restart = input('Play again? (y,n):n> ')
if restart == 'y':
start_menu()
gameplay_loop()
if restart == 'n':
print('Goodbye.')
sys.exit()
else:
print('Invalid input')
restart_game()
gameplay_loop()

我试着把这个添加到我的代码中,但它仍然只接受'Take'作为用户输入。

# invalid command
elif ('Take'+item) not in user_input:
print('Invalid inputn')

这是您期望的操作方式。我在公司里做了一些改变。我已经删除了你所有的"自动大写",所以你必须准确地输入命令。我已经删除了所有的递归调用,并将它们替换为循环——这不是递归的正确使用。

我也删除了你的块标题,因为我不想处理字符集。你可以把它加回去。

import sys
def start_menu():
# Print start menu and commands
print('<>' * 50)
print('You are a Spy visiting the Great Pyramid of Meereen. You must make your way from the top of then'
'Pyramid to the Dragon Pit. Collect all of the items along the way to help defeat the two Dragons.n'
'If you are successful you will put an end to Queen Daenerys reign and save the Seven Kingdoms.n'
'nHappy Adventuring!')
print('<>' * 50)
print('Input move: North, South, East or West')
print('Input "Take [item name]" to add item to inventory')
print('Input "Exit" to quit game')
print('<>' * 50)
# Dictionary of rooms and items
rooms = {
'Terrace': {'East': 'Daenerys Chambers'},
'Daenerys Chambers': {'West': 'Terrace', 'East': 'Barristan's Chambers', 'South': 'Royal Chambers',
'item': 'Dragon Necklace'},
'Barristan's Chambers': {'West': 'Daenerys Chambers', 'item': 'Barristan's Sword'},
'Royal Chambers': {'North': 'Daenerys Chambers', 'South': 'Torture Cells',
'West': 'Audience Chamber', 'East': 'Stables', 'item': 'Milk of the Poppy'},
'Audience Chamber': {'East': 'Royal Chambers', 'item': 'Torch'},
'Stables': {'West': 'Royal Chambers', 'item': 'Health Potion'},
'Torture Cells': {'North': 'Royal Chambers', 'East': 'Dragon Pit', 'item': 'Magic Potion'},
'Dragon Pit': {'West': 'Torture Cells', 'Item': 'Dragons'}
}
def gameplay_loop():
move_direction = ['North', 'South', 'East', 'West']
inventory = []
current_room = 'Terrace'
# Gameplay loop
while True:
# Display Inventory
print('Inventory', inventory, 'n')
if current_room == 'Terrace':
print('You are on the {}.n'.format(current_room))
else:
print('You are in the {}.'.format(current_room))
if current_room == 'Torture Cells':
print('A sign reads: "Beware of Dragon Pit: East"')
item = None
if 'item' in rooms[current_room]:
item = rooms[current_room]['item']
if item in inventory:
print('You have collected all of the items in this room.n')
item = None
else:
print('Item:', item, 'n')
# Display user input
user_input = input('Enter your move:' + 'n' + '> ')  # Movement control
print('')  # Space for visual formatting
#        user_input = user_input.title()  # Capitalize each word
print('<>' * 50)
if user_input in move_direction:
user_input = user_input
if user_input in rooms[current_room].keys():
current_room = rooms[current_room][user_input]
print(current_room)
print('<>' * 50)
else:
# for invalid movement
print('You can't go there!')
print('<>' * 50)
continue
# Check for exit command
elif user_input == 'Exit':
print('Thank you for playing!')
print('<>' * 50)
break
# invalid command
elif 'Take' not in user_input:
print('Invalid inputn')
continue
# What item did they want?
want = user_input[5:]
if want != item:
print("That item is not available.")
continue
# Update inventory
if current_room != 'Terrace' and item not in inventory:
inventory.append(item)
print('You found:', item)
print('<>' * 50)
# Check for game over
if len(inventory) == 6 and current_room == 'Dragon Pit':
print('nYou have defeated the Dragons and saved the Seven Kingdoms!')
print('Thanks for playing!')
elif len(inventory) < 6 and current_room == 'Dragon Pit':
print('nYou died.')
print('Collect all six items before facing the Dragons...')
while True:
# Restart or exit game
restart = input('Play again? (y,n):n> ')
if restart == 'y':
start_menu()
return True
if restart == 'n':
print('Goodbye.')
return False
print('Invalid input')
start_menu()
while gameplay_loop():
pass

要验证Take + Items,您需要读取输入并存储它们,如果我理解正确的话,如下所示。


# Check for Take in input and Item name
elif 'Take' in user_input:
item = user_input[5:]
if item in rooms[current_room].values():
inventory.append(item)
print('You have added {} to your inventory.'.format(item))
print('<>' * 50)
else:
print('You can't take that!')
print('<>' * 50)```

相关内容

  • 没有找到相关文章

最新更新