python - 石头剪刀布运行两次错误
问题描述
我是编程新手。我已经为石头剪刀布游戏编写了代码,但是有一个我似乎无法修复的错误。当游戏结束时,会询问用户是否想再玩一次。如果用户第一次回答“是”,然后再次播放,然后第二次回答“否”,则计算机出于某种原因再次询问用户是否想再次播放。在这种情况下,用户必须输入 no。这是因为尽管用户回答“否”,但答案会重置为“是”并重新开始。如何解决这个问题?
# This code shall simulate a game of rock-paper-scissors.
from random import randint
from time import sleep
print "Welcome to the game of Rock, Paper, Scissors."
sleep(1)
def theGame():
playerNumber = 4
while playerNumber == 4:
computerPick = randint(0,2)
sleep(1)
playerChoice = raw_input("Pick Rock, Paper, or Scissors. Choose wisely.: ").lower()
sleep(1)
if playerChoice == "rock":
playerNumber = 0
elif playerChoice == "paper":
playerNumber = 1
elif playerChoice == "scissors":
playerNumber = 2
else:
playerNumber = 4
sleep(1)
print "You cookoo for coco puffs."
print "You picked " + playerChoice + "!"
sleep(1)
print "Computer is thinking..."
sleep(1)
if computerPick == 0:
print "The Computer chooses rock!"
elif computerPick == 1:
print "The Computer chooses paper!"
else:
print "The Computer chooses scissors!"
sleep(1)
if playerNumber == computerPick:
print "it's a tie!"
else:
if playerNumber < computerPick:
if playerNumber == 0 and computerPick == 2:
print "You win!"
else:
print "You lose!"
elif playerNumber > computerPick:
if playerNumber == 2 and computerPick == 0:
print "You lose!"
else:
print "You win!"
replay()
def replay():
sleep(1)
playAgain = "rerun"
while playAgain != "no":
playAgain = raw_input("Would you like to play again?: ").lower()
if playAgain == "yes":
sleep(1)
print "Alright then brotha."
sleep(1)
theGame()
elif playAgain == "no":
sleep(1)
print "Have a good day."
sleep(1)
print "Computer shutting down..."
sleep(1)
else:
sleep(1)
print "What you said was just not in the books man."
sleep(1)
theGame()
解决方案
你应该在调用之后跳出循环theGame
。想象一下,你决定再玩 15 次。然后栈上有15个replay
循环,等着问你要不要再玩。因为playAgain
在"yes"
每个循环中,每个循环都会再次询问你,因为playAgain
不是"no"
推荐阅读
- python - 简单的for循环猜测python中的变量名
- node.js - 如何在猫鼬中查询嵌套的对象数组
- python - 我的带有线性回归线的散点图未显示
- javascript - R-Shiny:如何显示动画和使用 saveHTML() 函数创建的控件?
- html - 使用对象适合属性调整 html img 组件的大小
- forms - 如何使用 Colab 将谷歌表单下拉列表放到谷歌小部件 TabBar 上?
- flutter - Flutter如何将图片上传到ftp
- javascript - 如何将此字符串转换为数字数组?
- eclipse - 如何从 Eclipse 中单独下载 Eclipse 20221-09 的 Eclipse CVS 插件?
- r - R Shiny-fixedHeader 扩展工作,但 fixedColumns 不是。为什么?