如何重新开始一个简单的掷币游戏
我正在使用 Python 2.6.6
我只是想根据用户的输入从头开始重新启动程序。谢谢
import random
import time
print "You may press q to quit at any time"
print "You have an amount chances"
guess = 5
while True:
chance = random.choice(['heads','tails'])
person = raw_input(" heads or tails: ")
print "*You have fliped the coin"
time.sleep(1)
if person == 'q':
print " Nooo!"
if person == 'q':
break
if person == chance:
print "correct"
elif person != chance:
print "Incorrect"
guess -=1
if guess == 0:
a = raw_input(" Play again? ")
if a == 'n':
break
if a == 'y':
continue
#Figure out how to restart program
我对 continue 这个语句有点困惑。因为如果我使用了 continue,第一次输入 'y' 后就再也没有“再玩一次”的选项了。
4 个回答
0
你需要用 random.seed
来初始化随机数生成器。如果每次都用相同的值来调用它,那么从 random.choice 得到的值就会重复。
1
我建议:
- 把你的代码分成几个函数,这样看起来会更清晰。
- 使用有帮助的变量名称,让人一看就知道它们的作用。
- 不要把常量用掉(第一次运行代码后,你怎么知道要从多少次猜测开始呢?)
.
import random
import time
GUESSES = 5
def playGame():
remaining = GUESSES
correct = 0
while remaining>0:
hiddenValue = random.choice(('heads','tails'))
person = raw_input('Heads or Tails?').lower()
if person in ('q','quit','e','exit','bye'):
print('Quitter!')
break
elif hiddenValue=='heads' and person in ('h','head','heads'):
print('Correct!')
correct += 1
elif hiddenValue=='tails' and person in ('t','tail','tails'):
print('Correct!')
correct += 1
else:
print('Nope, sorry...')
remaining -= 1
print('You got {0} correct (out of {1})\n'.format(correct, correct+GUESSES-remaining))
def main():
print("You may press q to quit at any time")
print("You have {0} chances".format(GUESSES))
while True:
playGame()
again = raw_input('Play again? (Y/n)').lower()
if again in ('n','no','q','quit','e','exit','bye'):
break
2
在你想要重新开始循环的地方使用 continue 语句。就像你用 break
来退出循环一样,continue
语句会让循环重新开始。
虽然这不是针对你的问题,但我来讲讲怎么使用 continue
:
while True:
choice = raw_input('What do you want? ')
if choice == 'restart':
continue
else:
break
print 'Break!'
还有:
choice = 'restart';
while choice == 'restart':
choice = raw_input('What do you want? ')
print 'Break!'
输出 :
What do you want? restart
What do you want? break
Break!