【发布时间】:2020-04-27 19:31:48
【问题描述】:
我是编码新手,我创建的石头剪刀布游戏没有按预期运行。 如果有人输入了石头、纸或剪刀这个词,那么程序就会按预期工作。 但是,当有人输入石头、纸或剪刀以外的单词时,程序应该说“我不明白,请再试一次”,并提示用户输入另一个输入,它确实如此,但不是继续工作程序按预期结束。这是代码:
# The game of Rock Paper Scissors
import random
choices = ['rock', 'paper', 'scissors']
computer_choice = random.choice(choices)
selections = 'The computer chose ' + computer_choice + ' so'
computer_score = 0
user_score = 0
def choose_option():
user_choice = input('Please choose Rock, Paper or Scissors. (q to quit)\n>>> ')
while user_choice != 'q':
if user_choice in ['ROCK', 'Rock', 'rock', 'R', 'r']:
user_choice = 'rock'
elif user_choice in ['PAPER', 'Paper', 'paper', 'P', 'p']:
user_choice = 'paper'
elif user_choice in ['SCISSORS','Scissors', 'scissors', 'S', 's']:
user_choice = 'scissors'
else:
print("I don't understand, please try again.")
choose_option()
return user_choice
user_choice = choose_option()
while user_choice != 'q':
if user_choice == computer_choice:
print(selections + ' it\'s a tie')
elif (user_choice == 'rock' and computer_choice == 'scissors'):
user_score += 1
print(selections + ' you won! :)')
elif (user_choice == 'paper' and computer_choice == 'rock'):
user_score += 1
print(selections + ' you won! :)')
elif (user_choice == 'scissors' and computer_choice == 'paper'):
user_score += 1
print(selections + ' you won! :)')
elif (user_choice == 'rock' and computer_choice == 'paper'):
computer_score += 1
print(selections + ' you lost :(')
elif (user_choice == 'paper' and computer_choice == 'scissors'):
computer_score += 1
print(selections + ' you lost :(')
elif (user_choice == 'scissors' and computer_choice == 'rock'):
computer_score += 1
print(selections + ' you lost :(')
else:
break
print('You: ' + str(user_score) + " VS " + "Computer: " + str(computer_score))
computer_choice = random.choice(choices)
selections = 'The computer chose ' + computer_choice + ' so'
user_choice = choose_option()
【问题讨论】:
-
需要从递归调用返回,即
else子句中的return choose_option()。 -
附带说明,您可以使用
if user_choice.lower() in ['rock','r']:节省一些打字时间 -
甚至使用正则表达式 -
if re.search(r'(scissors|s)', user_choice, flags=re.I)
标签: python python-3.x