#RockPS
import random
Choices=['R','P','S']
UserScore=0
CpuScore=0
Games=0
while Games<6:
UserChoice=input('Rock, paper or scissors? (Type R, P or S respectively)')
if UserChoice in Choices:
Games+=1
CpuChoice = random.choice(Choices)
if UserChoice == 'S' and CpuChoice == 'P':
UserScore+=1
if UserChoice == 'P' and CpuChoice == 'R':
UserScore+=1
if UserChoice == 'R' and CpuChoice == 'S':
UserScore+=1
if UserChoice == 'S' and CpuChoice == 'R':
CpuScore+=1
if UserChoice == 'P' and CpuChoice == 'S':
CpuScore+=1
if UserChoice == 'R' and CpuChoice == 'P':
CpuScore+=1
print(UserScore, CpuScore)
if UserScore>CpuScore:
print('Well done, you won!')
if UserScore==CpuScore:
print('You tied!')
if UserScore<CpuScore:
('Unlucky, you lost.')
我是Python的新手,所以我可能错过了一些明显的东西。程序运行良好。这是一个石头,纸或剪刀游戏。进行5场比赛,比分列在游戏结束时。目前,它只说 1 0、0 0 或 0 1,只计算 1 场比赛。我不确定这是为什么。我认为这与我的缩进有关,因为我没有看到我的循环有问题。
怎么回事:这部分代码
while Games<6:
UserChoice=input('Rock, paper or scissors? (Type R, P or S respectively)')
if UserChoice in Choices:
Games+=1
执行 6 次,但从这里开始的所有剩余行:
CpuChoice = random.choice(Choices)
if UserChoice == 'S' and CpuChoice == 'P':
UserScore+=1
if UserChoice == 'P' and CpuChoice == 'R':
UserScore+=1
仅在循环迭代完成后执行一次。所有if UserChoice ==
行都应缩进,以便它们成为环体的一部分。
是的,您的缩进似乎确实是问题所在。您应该识别该行
CpuChoice = random.choice(Choices)
然后是线条
if UserChoice == ...
与线路相同
if UserChoice in Choices:
当标识返回到与while
相同的级别时,while
循环的主体结束。因此,目前,所有if UserChoice == ...
条件仅在while
循环完成后检查一次(这就是为什么您看到1 0
、0 0
或0 1
的原因)。如果您识别我建议的线条,那么它们将成为while
循环体的一部分。