Python 3 : Rock, Paper, Scissor game - 如何定义获胜次数和选择次数

Posted

技术标签:

【中文标题】Python 3 : Rock, Paper, Scissor game - 如何定义获胜次数和选择次数【英文标题】:Python 3 : Rock, Paper, Scissor game - how to define counts for the wins and picks 【发布时间】:2018-03-21 22:17:08 【问题描述】:

我是 Python 新手。需要在 Python 3 中创建游戏 Rock, Paper, Scissors 并在游戏结束时打印出来:

The number of rounds the computer has won.
The number of rounds the user has won.
The number of rounds that ended in a tie
The number of times the user selected each weapon (Rock, Paper, Scissors).

注意:计算机应该根据用户之前选择的武器选择最有可能击败用户的武器,但它的选择直到稍后才会显示,因此用户看不到它.因为该计算机会记录用户选择每种武器(石头、纸或剪刀)的次数。

例如,如果用户每次选择石头和纸 3 次,而只选择剪刀 1 次,或者如果用户选择每种武器的次数相同,则没有最频繁使用的武器由用户;在这种情况下,计算机可以选择任何武器。

接下来是我的代码:

# Import random function
import random

# After the round ask the user if he/she would like to play the game again
def display_intro():
    print("Welcome to Rock, Paper and Scissors Game!")
    play_game = input("Would you like to play with me?\n"
                  "y/n").lower()
    if play_game == "y" or play_game == "yes" or play_game == "Y":
        print("Let\'s start playing!")
        get_comp_choice()
    elif play_game == "n" or play_game == "no" or play_game == "N":
        print("Thanks for playing")
        print("Computer won", compWinCt, "times.")"" \
        print("User won", userWinCt, "times.")
        print("Draw games count is: ",drawCt)
        print("User picked Rock", userRockCt, "times.")
        print("User picked Paper", userPaperCt, "times.")
        print("User picked Scissors", userScissors, "times.")
        quit()
    else:
        print("That's now a valid choice. Please try again!")
    display_intro()


# define random choice pick
def get_random_choice():
    comp_choice = random.randint(1, 3)
    if comp_choice == 1:
        comp_choice = "r"
    elif comp_choice == 2:
        comp_choice = "p"
    elif comp_choice == 3:
        comp_choice = "s"
    return comp_choice

# define computer choice base on what user has chosen in previous rounds
def get_comp_choice():
    if userRockCt == 0 and userPaperCt == 0 and userScissorsCt == 0:
        return get_random_choice()
    else:
        if (userRockCt > userPaperCt) and (userRockCt > userScissorsCt):
           return comp_choice == "r"
        elif (userPaperCt > userRockCt) and (userPaperCt > userScissorsCt):
            return comp_choice == "p"
        elif (userScissorsCt > userPaperCt) and (userScissorsCt > userRockCt):
            return comp_choice == "s"

def main():
while True:
    # set count for a zero
    userRockCt = 0
    userPaperCt = 0
    userScissorsCt = 0
    compWinCt = 0
    userWinCt = 0
    drawCt = 0
    # Get computer choice
    comp_choice = get_comp_choice()
    # Get user choice from the input
    user_choice = input("Please enter from the menue: \n"
                        "r for rock,"
                        "p for paper"
                        "s for scissors"
                        "q to quit")

    # Check who has won /lost or if the game is draw
    # Get the count for how many times user picke Rock, Paper or Scissors
    # Get the count for how many times won computer and user and the count for the draw
    while comp_choice == "r":
        if user_choice == "r":
            print("This is a DRAW. You chose Rock and Computer chose Rock.")
            userRockCt += 1
            drawCt += 1
        elif user_choice == "p":
            print("YOU WIN. You chose Paper and Computer chose Rock. Paper covers Rock.")
            userPaperCt += 1
            userWinCt += 1
        elif user_choice == "s":
            print("YOU LOSE. You chose Scissors and Computer chose Rock. Rock breaks Scissors.")
            userScissorsCt += 1
            compWinCt += 1
        else:
            print("Try again")
        display_intro()

    while comp_choice == "p":
        if user_choice == "r":
            print("YOU LOSE. You chose Rock and Computer chose Paper. Paper covers Rock.")
            userRockCt += 1
            compWinCt += 1
        elif user_choice == "p":
            print("This is a DRAW. You chose Rock and Computer chose Rock.")
            userPaperCt += 1
            drawCt += 1
        elif user_choice == "s":
            print("YOU WIN. You chose Scissors and Computer chose Paper. Scissors cut Paper.")
            userScissorsCt += 1
            userWinCt += 1
        display_intro()

    while comp_choice == "s":
        if user_choice == "r":
            print("YOU WIN. You chose Rock and Computer chose Scissors. Rock breaks Scissors.")
            userRockCt += 1
            userWinCt += 1
        elif user_choice == "p":
            print("YOU LOSE. You chose Paper and Computer chose Scissors. Scissors cut Paper.")
            userPaperCt += 1
            compWinCt += 1
        elif user_choice == "s":
            print("This is a DRAW. You chose Scissors and Computer chose Scissors.")
            userScissorsCt += 1
            drawCt += 1
        display_intro()


main()

我不知道我是否放错了定义函数的顺序或遗漏了什么。当我运行代码时,我得到了这个错误。

Traceback (most recent call last):
  File "C:/Users/.../Test", line 123, in <module>
    main()
  File "C:/Users/.../Test", line 64, in main
    comp_choice = get_comp_choice()
  File "C:/Users/.../Test", line 43, in get_comp_choice
    if userRockCt == 0 and userPaperCt == 0 and userScissorsCt == 0:
NameError: name 'userRockCt' is not defined

Process finished with exit code 1

只要看一下代码,我就知道 userPaperCt 和 get_comp_choice 的 userScissorsCt 也会出现同样的问题

在 def display_intro() 中使用 compWinCt、userWinCt 和 DrawCt

我见过一些使用 global 的例子,但我试图避免使用它。

【问题讨论】:

我认为 userRockCt 仅在主函数中本地化,因为变量仅存在于该范围内。但是,如果您不想使用它,将其设为全局可以解决此错误。您必须将 main 函数中的这个局部变量作为参数传递给该 get_comp_choice。这个link 会很有用。 @ShamveelAhammed 非常感谢您的回复!问题,如果我决定使用全局函数 - 它是如何工作的?我只是将 userRockCt 等分配给它? 是的。只需在任何函数之外声明变量,例如在导入之后,然后只需在函数中声明它是全局的(这将使其他函数可以访问它)。检查此link 以获取示例使用。 @ShamveelAhammed 谢谢你的回答!我会试试你的建议! 【参考方案1】:

将“userRockCt”声明为全局变量可以解决此问题。

# Import random function
import random

# Declaring the variable here
userRockCt = 0

# Rest of the code goes here

def main():
while True:
   # Declaring the variable as global here
   # set count for a zero
   global userRockCt

   # rest of your code

main()

【讨论】:

以上是关于Python 3 : Rock, Paper, Scissor game - 如何定义获胜次数和选择次数的主要内容,如果未能解决你的问题,请参考以下文章

模拟AtCoDeer and Rock-Paper

python 实现剪刀石头布(三局两胜)

rock-paper-scissors

GYM 101667H Rock Paper Scissors(FFT)

IIPP迷你项目“Rock-paper-scissor-lizard-Spock”

IIPP迷你项目“Rock-paper-scissor-lizard-Spock”