首页 > 解决方案 > 石头剪刀布总是让我赢

问题描述

我是一名新程序员,正在尝试通过创建一个石头剪刀布游戏来熟悉 if else 语句。我的问题是代码总是让我赢。此外,我的 while 循环实际上不会循环,因此非常感谢您对这些东西的任何帮助。谢谢!:)

编码:

from random import randint

t = ["Rock", "Paper", "Scissors"]

computer = t[randint(0, 2)]

player = False

while player == False:
    player = input("Rock, Paper, or Scissors: ").lower()
    if player == computer:
        print("Computer:" + player.capitalize())
        print("Tie!")
    elif player == "rock":
        if computer == "Paper":
            print("Computer: Paper")
            print("You lose")
        else:
            print("Computer: Scissors")
            print("You Win!")
    elif player == "paper":
        if computer == "Scissors":
            print("Computer: Scissors")
            print("You Lose!")
        else:
            print("Computer: Rock")
            print("You win")
    elif player == "scissors":
        if computer == "Rock":
            print("Computer: Rock")
            print("You lose!")
        else:
            print("Computer: Paper")
            print("You Win!")
    else:
        print("Invalid input. Try again!")

player = False
computer = t[randint(0, 2)]

标签: pythonpython-3.x

解决方案


游戏不会重复,因为player == False在玩家做出选择后,您的条件永远不会成立。它总是包含玩家的最后选择,而不是False.

不要使用该while条件,而是允许用户输入类似quit. 然后在运行其余代码之前检查它,然后跳出循环。

您可以使用random.choice()来从列表中选择一个项目,而不是randint().

计算机的选择需要在循环中。否则,玩家总是可以获胜,因为计算机的选择永远不会改变。

from random import choice

t = ["Rock", "Paper", "Scissors"]

while True:
    player = input("Rock, Paper, Scissors, or quit: ").lower()
    if player == 'quit':
        break
    computer = choice(t)
    if player == computer:
        print("Computer:" + player.capitalize())
        print("Tie!")
    elif player == "rock":
        if computer == "Paper":
            print("Computer: Paper")
            print("You lose")
        else:
            print("Computer: Scissors")
            print("You Win!")
    elif player == "paper":
        if computer == "Scissors":
            print("Computer: Scissors")
            print("You Lose!")
        else:
            print("Computer: Rock")
            print("You win")
    elif player == "scissors":
        if computer == "Rock":
            print("Computer: Rock")
            print("You lose!")
        else:
            print("Computer: Paper")
            print("You Win!")
    else:
        print("Invalid input. Try again!")

推荐阅读