我的石头、布、剪刀密码怎么了?

2024-09-28 17:30:14 发布

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

使用python,我必须为学校创建一个石头-布-剪刀游戏,用户在电脑上玩。计算机的选择也必须是随机的。当我试着运行这段代码时,它说有语法错误,但不是它所在的位置。有人能帮忙吗?你知道吗

    import random

print("Welcome to rock paper scissors.")

player = False

while player == False:
    print(" ")
    print("Press 1 for Rock")
    print("Press 2 for Paper")
    print("Press 3 for Scissors")

    User = int(input("Rock, Paper or Scissors?"))
    Com = random.randrange(1,3)

    if (User == 1) and (Com == 1):
        player = False
    print("Its a draw!")

    elif (User == 2) and (Com == 1):
        player = True
    print("You win!")

    elif (User == 3) and (Com == 1):
        player = True
    print("You lose!")

    elif (User == 1) and (Com == 2):
        player = True
    print("You lose!")

    elif (User == 2) and (Com == 2):
        player = False
    print("Its a draw!")

    elif (User == 3) and (Com == 2):
        player = True
    print("You win!")

    elif (User == 1) and (Com == 3):
        player = True
    print("You win!")

    elif (User == 2) and (Com == 3):
        player = True
    print("You lose!")

    elif (User == 3) and (Com == 3):
        player = False
    print("Its a draw! You both entered scissors.")

    else:
        print("Make sure to enter a number from 1 - 3")

Tags: andcomyoufalsetrueforwinits
2条回答

就像@jedruniu说的,你有不正确的缩进。另外,我还自由地清理了您的代码,这样就不那么混乱了:

import random

print("Welcome to rock paper scissors.")

draw = True

while draw:
    print()
    print("Press 1 for Rock")
    print("Press 2 for Paper")
    print("Press 3 for Scissors")
    User = int(input("Rock, Paper or Scissors?"))
    Com = random.randint(1,3)

    if User == Com:
        print("Its a draw!")

    else:
        draw = False #so it doesn't repeat

        if (User == 2) and (Com == 1):
            print("You win!")

        elif (User == 3) and (Com == 1):
            print("You lose!")

        elif (User == 1) and (Com == 2):
            print("You lose!")

        elif (User == 3) and (Com == 2):
            print("You win!")

        elif (User == 1) and (Com == 3):
            print("You win!")

        elif (User == 2) and (Com == 3):
            print("You lose!")

        else:
            print("Make sure to enter a number from 1 - 3")

看这里:

if (User == 1) and (Com == 1):
    player = False
print("Its a draw!")

elif (User == 2) and (Com == 1):
    player = True
print("You win!")

带有print("Its a draw!")的print语句不属于if。在ifelif之间不能有任何“松散”的东西。你知道吗

您的导入也缩进,但我相信这是格式错误。你知道吗

它修复了您的错误,但请注意,您的命名约定并没有说明太多关于代码的内容。你知道吗

相关问题 更多 >