gpt4 book ai didi

python - 如何在Python中重复石头、剪刀、布的游戏

转载 作者:行者123 更新时间:2023-12-01 00:37:06 40 4
gpt4 key购买 nike

我用Python做了一个石头、剪刀、布的游戏。如果用户输入"is",我如何让游戏重复进行?当用户输入除了石头、布或剪刀之外的任何内容时,我的代码似乎进入永无休止的循环

此外,我正在尝试了解何时何地应该使用函数。如果您能展示一种 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/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com