gpt4 book ai didi

python - 如何在简单的 Python 游戏中循环?

转载 作者:太空宇宙 更新时间:2023-11-03 17:40:52 26 4
gpt4 key购买 nike

我对 Python 很陌生,但编写了一个简单的石头剪刀布游戏。

其代码如下:

from __future__ import print_function
import random

name = raw_input("Hi, I'm PyVa. What is your name: ")
print('Hi',name, end='.')
yesorno = raw_input(' Would you like to play Rock, Paper, Scissors?: ')
yesorno = str(yesorno)



if yesorno == str('Yes'):
choices = ['Rock', 'Paper', 'Scissors']
print('Ok')
your_choice = raw_input('Choose Rock, Paper or Scissors: ')
print('My turn...')

my_choice = random.choice(choices)
print('I choose,', my_choice)
if your_choice == my_choice:
print('We both choose the same, it is a draw.')
elif your_choice == 'Rock' and my_choice == 'Paper':
print('I win!')
elif your_choice == 'Scissors' and my_choice == 'Paper':
print('You win!')
elif your_choice == 'Paper' and my_choice == 'Rock':
print('You win!')
elif your_choice == 'Paper' and my_choice == 'Scissors':
print('I win!')
elif your_choice == 'Rock' and my_choice == 'Scissors':
print('You win!')
elif your_choice == 'Scissors' and my_choice == 'Rock':
print('I win!')

again = raw_input('Would you like to play again?:')

#this is where I would like to loop to the start depending on input.



else:
print('Ok, maybe we can play later, bye.')

现在我可以想象这根本不是优雅的代码,并且必须有更精确的方法来编写我想要做的事情。 (如有时间请指点)。

我主要关心的是如何在每个游戏结束后正确插入循环以返回到第二个 block ,即。根据用户的 raw_input 开始或游戏,或简单地结束。

非常感谢您提供的任何帮助。

最佳答案

给你:

from __future__ import print_function
import random

name = raw_input("Hi, I'm PyVa. What is your name: ")
print('Hi',name, end='.')
n = 0
while True:
if 'y' in raw_input('Would you like to play Rock, Paper, Scissors?: ').lower() or n > 0:
my_choice = random.choice(['rock', 'paper', 'scissors'])
print('Ok')
your_choice = raw_input('Choose Rock, Paper or Scissors: ').lower()
print('My turn...')
print('I choose,', my_choice)
if your_choice == my_choice:
print('We both choose the same, it is a draw.')
elif your_choice in ['rock', 'scissors'] and my_choice == 'paper':
print('I win!')
elif your_choice == 'paper' and my_choice in ['rock', 'scissors']:
print('You win!')
elif your_choice == 'rock' and my_choice == 'scissors':
print('You win!')
elif your_choice == 'scissors' and my_choice == 'rock':
print('I win!')
n += 1
if not 'y' in raw_input('Would you like to play again?:').lower():
break

#this is where I would like to loop to the start depending on input.

现在它也不区分大小写,当游戏退出或你因为不小心忘记写下以大写字母开头的答案而输掉时,有点烦人。我还使用“in”稍微简化了它

关于python - 如何在简单的 Python 游戏中循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30577473/

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