基本的石头、布或剪刀程序

2024-10-03 21:36:01 发布

您现在位置:Python中文网/ 问答频道 /正文

更新代码:

  #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

else:
    print('Only R, P or S are allowed')


print(UserScore, CpuScore)
if UserScore>CpuScore:
    print('Well done, you won!')
if UserScore==CpuScore:
    print('You tied!')
if UserScore<CpuScore:
    ('Unlucky, you lost.')

还有一个问题。当分数被打印出来时,每种情况下都只显示10分,这意味着大多数获胜的玩家。它应该计算每场比赛,例如32或41


Tags: orand代码importyouifrandomgames
3条回答

您的代码中存在许多问题:

  1. 您没有正确使用random.choice。在
  2. 每次用户播放前都应该调用该函数。如果你叫它一次,它每次都会保持不变。在
  3. 要求用户输入一次值,因为input(...)函数在循环的外部被调用一次。在
  4. 这不是命名变量的方法(至少在Python中是这样)
  5. 多次使用if/elif执行相同的操作不是使用or

所以,你的代码应该是这样的:

#RockPS
import random

game_choices = ['R','P','S']
user_score = 0
cpu_score = 0
games = 0

while games<6:
    user_choice = input('Rock, paper or scissors? (Type R, P or S respectively)')
    if user_choice in game_choices:
        games += 1
        cpu_choice = random.choice(cpu_choices)
        if (user_choice == 'S' and cpu_choice == 'P') or \
           (user_choice == 'P' and cpu_choice == 'R') or \
           (user_choice == 'R' and cpu_choice == 'S'):
            user_score += 1
        elif (user_choice == 'S' and cpu_choice == 'R') or \
             (user_choice == 'P' and cpu_choice == 'S') or \
             (user_choice == 'R' and cpu_choice == 'P'):
            cpu_score += 1
    else:
        print('Only R, P or S are allowed')

print(user_score, cpu_score)
if user_score>cpu_score:
    print('Well done, you won!')
elif user_score == cpu_score:
    print('You tied!')
elif user_score<cpu_score:
    print('Unlucky, you lost.')

你还是可以改进的。我加了一张支票,确保字母不是RPS就是RPS。而这一大块的条件,你可以通过使用一个返回赢家的函数使它们变短(例如,如果cpu赢了,则返回1,如果玩家赢了,则返回0),等等。。。在

你需要在你的循环里输入。别忘了增加玩游戏的次数。在

可能不是唯一的问题,但我马上想到的是:排队

random.choice(CpuChoice)

不会将CpuChoice设置为计算机的随机选择。随机选择()返回一个随机选择,但不会将其存储在任何位置。你想要吗

^{pr2}$

…并且您希望在循环内执行此操作(收集用户输入,并可能输出每轮的结果),除非CPU每次都执行相同的选择,这将很容易被击败:)

你也不会在任何地方增加游戏——实际上,你可能需要一个for循环,因为你只想运行6次。在

相关问题 更多 >