Python 剪刀布归还问题
所以,我遇到的问题是,当我的计数器试图将数字相加时,它会不断重置 我试着想出一种方法把计数器部分变成函数,但我想不出来Python 剪刀布归还问题,python,Python,所以,我遇到的问题是,当我的计数器试图将数字相加时,它会不断重置 我试着想出一种方法把计数器部分变成函数,但我想不出来 winP1=0 winP2=0 tie=0 ans = input('Would you like to play ROCK, PAPER, SCISSORS?: ') while ans == 'y': p1c = input('Player 1 enter either R,P, or S: ') #p1c stands for "player 1 choice
winP1=0
winP2=0
tie=0
ans = input('Would you like to play ROCK, PAPER, SCISSORS?: ')
while ans == 'y':
p1c = input('Player 1 enter either R,P, or S: ') #p1c stands for "player 1 choice"
p2c = input('Player 2 enter either R,P, or S: ')
ans = input('Would you like to play again: ')
def game(p1c,p2c):
if p1c == p2c: #if its a tie we are going to add to the Tie variable
return 0
elif p1c == 'R' and p2c == 'P': #We will only set the Player 1 wins because
return 1 #player 2 wins can be set as else
elif p1c == 'P' and p2c == 'S':
return 1
elif p1c == 'S' and p2c == 'R':
return 1
else:
return -1
result = game(p1c,p2c)
if result == -1:
winP2 += 1
if result == 0:
tie += 1
else:
winP1 +=1
print('Player 1 won {} times. \nPlayer 2 won {} times. \nThere were {} ties.'.format(winP1,winP2,tie))
欢迎使用StackOverflow和Python编程!我希望你在这里过得愉快 您的计数器不断重置,因为对于系统而言,您只玩一个游戏:
while ans == 'y':
p1c = input('Player 1 enter either R,P, or S: ') #p1c stands for "player 1 choice"
p2c = input('Player 2 enter either R,P, or S: ')
ans = input('Would you like to play again: ')
我将在您的代码中移动一些东西,以获得您想要的结果,并进行最小程度的编辑,希望这将显示您需要做什么。你在正确的轨道上
我们将使用一个名为state
的字典来跟踪游戏状态并传递它
state = {
'winP1':0,
'winP2':0,
'tie':0
}
def game(p1c,p2c):
if p1c == p2c: #if its a tie we are going to add to the Tie variable
return 0
elif p1c == 'R' and p2c == 'P': #We will only set the Player 1 wins because
return 1 #player 2 wins can be set as else
elif p1c == 'P' and p2c == 'S':
return 1
elif p1c == 'S' and p2c == 'R':
return 1
else:
return -1
def process_game(p1c, p2c, state): # Move this into a function
result = game(p1c,p2c)
if result == -1:
state['winP2'] += 1
if result == 0:
state['tie'] += 1
else:
state['winP1'] +=1
while ans == 'y':
p1c = input('Player 1 enter either R,P, or S: ') #p1c stands for "player 1 choice"
p2c = input('Player 2 enter either R,P, or S: ')
process_game(p1c, p2c, state)
ans = input('Would you like to play again: ')
print('Player 1 won {} times. \nPlayer 2 won {} times. \nThere were {} ties.'.format(state['winP1'],state['winP2'],state['tie']))
似乎在您的程序中,while循环将永远持续。@alKid No,它不会根据用户输入在while循环的最后一行中进行“ans”更改。@ChristianTernus我尝试使用的是,但现在我遇到了分配前引用的局部变量“tie”问题。我尝试使用的是,但现在遇到了分配前引用的局部变量“tie”问题。对!我加入了一个
global
声明,这通常不是一个好主意,但可以完成工作。实际上,你要做的是将游戏状态移动到它自己的对象中,并传递该对象。我不想问,但我还没有讨论全局的想法,我宁愿不使用它。你能给我看一下比赛状态吗?是的,我记得以前见过这样的场面!我现在开始工作了,非常感谢你,没问题。快乐编码!