剪刀石巨蟒游戏



这是我尝试创建纸、石头和剪刀游戏while循环似乎有一个错误;roundNum未定义";,请帮忙?

import random
options = ['rock','paper','scissors']
def game(rounds):
roundNum = 1
playerScore = 0
computerScore = 0
while roundNum <= rounds:
print('Round Number '+ str(roundNum))
Player = input('Please choose rock, paper or scissors')
computer =  options[random.randint(0,2)]
print(computer)

我如何创建代码来询问付款人是否想再次玩?如果是,再次运行代码

确保您的缩进是正确的。

import random
options = ['rock','paper','scissors']
def game(rounds):
roundNum = 1
playerScore = 0
computerScore = 0
while roundNum <= rounds:
print('Round Number '+ str(roundNum))
Player = input('Please choose rock, paper or scissors')
computer =  options[random.randint(0,2)]
print(computer)

问题在于while循环的缩进。

当函数game和while处于同一级别时,游戏函数中声明的任何对象都将超出while循环的范围/不可访问。

在这种情况下,一个简单的选项卡将解决如下问题:

import random
options = ['rock','paper','scissors']
def game(rounds):
roundNum = 1
playerScore = 0
computerScore = 0
while roundNum <= rounds:
print('Round Number '+ str(roundNum))
Player = input('Please choose rock, paper or scissors')
computer =  options[random.randint(0,2)]
print(computer)

您得到错误RoundNum is not defined的原因是您在函数内部定义变量,这意味着您必须调用函数game()来定义三个变量roundNumplayerScorecomputerScore。为了解决这个问题,我们删除了game()函数,并在主脚本中定义了三个变量,如下所示:

import random
options = ['rock', 'paper', 'scissors']
roundNum = 1 # Defines the roundNum variable
playerScore = 0
computerScore = 0
def game(rounds):
while roundNum <= rounds:
print('Round Number ' + str(roundNum)
Option = input('Please choose rock, paper, or scissors > ')
Computer = options[random.randint(0, 2)] 
# After all the rounds are finished, ask if the player wants to play again
x = input("Do you want to play again? ") 
# If they say yes, start a new round of Rock, paper, Scissors
if x.lower() == "yes":
game(1)
# If they don't want to play then exit the program
if x.lower() == "no":
print("Bye")        
exit()
game(1)

编辑:如果你想问玩家是否想再次玩,只需调用变量中的输入函数,然后检查玩家说了什么,如果他们说是,则开始一个新的石头、剪刀纸游戏,如果他们不想,则退出程序

最新更新