我用python做过石头,纸,剪刀的游戏。如果用户输入yes,我如何让游戏重复进行?当用户输入除了石头,纸或剪刀以外的任何东西时,我的代码似乎陷入了永无止境的循环

我也试图学习何时何地应该使用函数。如果您可以显示一种将完成的代码分离为功能的pythonic方法,我将不胜感激。

import random

a = ["rock", "paper", "scissors"]

word = input('Enter rock, paper, or scissors: ')

def game():
    while True:
        try:
            if word not in a:
                raise ValueError #this will send it to the print message and back to the input option
            break
        except ValueError:
            print(" You must enter rock, paper, or scissors.")


    comp_draw = random.choice(a)
    print('The computer drew ' + comp_draw)

    if comp_draw == 'rock' and word=='rock':
        print('It was a tie')
    elif comp_draw == 'paper' and word=='paper':
        print('It was a tie')
    elif comp_draw == 'scissors' and word=='scissors':
        print('It was a tie')

    elif comp_draw == 'paper' and word=='rock':
        print('you lost')
    elif comp_draw == 'rock' and word=='paper':
        print('you won!')

    elif comp_draw == 'rock' and word=='scissors':
        print('you lost')
    elif comp_draw == 'scissors' and word=='rock':
        print('you won!')

    elif comp_draw == 'scissors' and word=='rock':
        print('you won!')
    elif comp_draw == 'scissors' and word=='rock':
        print('you won!')

game()


play_again = input('would you like to play again: ')

最佳答案

没什么大不了的,只需要一个循环

import random

a = ["rock", "paper", "scissors"]

word = input('Enter rock, paper, or scissors: ')

def game():
    while True:
        try:
            if word not in a:
                raise ValueError #this will send it to the print message and back to the input option
            break
        except ValueError:
            print(" You must enter rock, paper, or scissors.")


    comp_draw = random.choice(a)
    print('The computer drew ' + comp_draw)

    if comp_draw == 'rock' and word=='rock':
        print('It was a tie')
    elif comp_draw == 'paper' and word=='paper':
        print('It was a tie')
    elif comp_draw == 'scissors' and word=='scissors':
        print('It was a tie')

    elif comp_draw == 'paper' and word=='rock':
        print('you lost')
    elif comp_draw == 'rock' and word=='paper':
        print('you won!')

    elif comp_draw == 'rock' and word=='scissors':
        print('you lost')
    elif comp_draw == 'scissors' and word=='rock':
        print('you won!')

    elif comp_draw == 'scissors' and word=='rock':
        print('you won!')
    elif comp_draw == 'scissors' and word=='rock':
        print('you won!')


play_again = "yes"

while play_again == "yes":

    game()

    play_again = input('would you like to play again: ').lower()

关于python - 如何在python中重复石头,纸,剪刀的游戏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57658689/

10-12 21:40