【问题标题】:Rock-Paper-Scissors Game石头剪刀布游戏
【发布时间】:2016-01-16 09:52:47
【问题描述】:

我目前非常坚持这个石头,纸,剪刀程序,非常感谢一些帮助。我浏览了其他有关石头、纸、剪刀程序的帖子,但我仍然卡住了。

我目前遇到的错误是当我要求用户选择“Rock”、“Paper”或“Scissors”时,它会继续询问几次,然后出现错误。此外,在我看来,我看到的大部分帖子都涉及我在课堂上没有使用过的概念,所以我对它们感到不舒服。

      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

【问题讨论】:

  • 鉴于choices 包含小写字符串,您认为input("...").lower() 将如何工作?另外,请阅读python.org/dev/peps/pep-0008
  • 检查您的清单。是小写的吗?

标签: python loops if-statement


【解决方案1】:

你的代码有几个问题:

首先是您将user input 转换为小写,但您的列表项不是。所以检查会失败。

choices = [ 'rock', 'paper', 'scissors' ]

第二件事是你调用choice(randnum) 会抛出一个错误,因为你必须使用[] 从列表中检索元素。

cptrchoice = choices[randnum]

第三种情况是如果你输入了无效的字符串。你只检查if,但你需要while loop

while (usrchoice not in choices):
    usrchoice = getUserChoice() #input("\nChoose again from Rock, Paper or Scissors: ").lower()

第四个在declareWinner,你的paramsusercomputer,但是你在if条件下使用usrchoicecptrchoice

def declareWinner(usrchoice, cptrchoice):
    if usrchoice == cptrchoice:

试试这个并试一试

【讨论】:

    猜你喜欢
    • 2022-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多