gpt4 book ai didi

python - 石头剪刀布返回问题

转载 作者:行者123 更新时间:2023-11-30 23:32:08 26 4
gpt4 key购买 nike

所以我遇到的问题是我的计数器在尝试将数字相加时不断重置我尝试找出一种方法将计数器部分变成一个函数,但我无法弄清楚

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']))

关于python - 石头剪刀布返回问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19532407/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com