我目前非常喜欢这种摇滚,纸张,剪刀程序,非常感谢一些帮助。我查看过有关摇滚,纸张,剪刀节目的其他帖子,但我仍然坚持。
我目前收到的错误是当我要求用户选择“摇滚”,“纸张”时。或者'剪刀'它会继续问几次然后我得到一个错误。另外,在我看来,我看到的很多帖子都涉及到我在课堂上没有使用的概念,所以我对它们感到不舒服。
choices = [ 'Rock', 'Paper', 'Scissors' ]
# 1. Greetings & Rules
def showRules():
print("\n*** Rock-Paper-Scissors ***\n")
print("\nEach player chooses either Rock, Paper, or Scissors."
"\nThe winner is determined by the following rules:"
"\n Scissors cuts Paper -> Scissors wins"
"\n Paper covers Rock -> Paper wins"
"\n Rock smashes Scissors -> Rock wins\n")
# 2. Determine User Choice
def getUserChoice():
usrchoice = input("\nChoose from Rock, Paper or Scissors: ").lower()
if (usrchoice not in choices):
usrchoice = input("\nChoose again from Rock, Paper or Scissors: ").lower()
print('User chose:', usrchoice)
return usrchoice
# 3. Determine Computer choice
def getComputerChoice():
from random import randint
randnum = randint(1, 3)
cptrchoice = choices(randnum)
print('Computer chose:', cptrchoice)
return randnum
# 4. Determine Winner
def declareWinner(user, computer):
if usrchoice == cptrchoice:
print('TIE!!')
elif (usrchoice == 'Scissors' and cptrchoice == 'Rock'
or usrchoice == 'Rock' and cptrchoice == 'Paper'
or usrchoice == 'Paper' and cptrchoice == 'Scissors'):
print('You lose!! :(')
else:
print('You Win!! :)')
#5. Run program
def playGame():
showRules() # Display the title and game rules
user = getUserChoice() # Get user selection (Rock, Paper, or Scissors)
computer = getComputerChoice() # Make and display computer's selection
declareWinner(user, computer) # decide and display winner
答案 0 :(得分:1)
您的代码几乎没有问题:
首先,您要将user input
转换为小写,但您的列表项不是。因此检查将失败。
choices = [ 'rock', 'paper', 'scissors' ]
第二件事是你调用选择(randnum)会抛出错误,因为你必须使用[]
从列表中检索元素。
cptrchoice = choices[randnum]
如果您输入无效字符串,则会发生第三种情况。您只需查看if
,但需要while loop
while (usrchoice not in choices):
usrchoice = getUserChoice() #input("\nChoose again from Rock, Paper or Scissors: ").lower()
第四个是declareWinner
,params
是user
和computer
,但是你在{{1}使用usrchoice
和cptrchoice
条件
if
试试这个并试一试