程序退出时重复确认
Repeated confirmation at program exit
我正在 Python 编写剪刀石头布游戏。但这是错误:
如果我玩了8次我想退出,游戏也会问我8次。
例子:我玩了5次
游戏问我:Do you want to exit? yes/no.
当我说(写)是时,游戏再次询问我,这种情况5次。
我是Python编程的初学者,我真的不明白为什么会这样。
你能帮帮我吗?
我正在 Windows 中编程并使用命令行来执行程序。 (不知道会不会影响程序的正常运行。)
这是代码。还没完:
class RPS_Game(object):
def Check(self):
P1 = raw_input("Player 1: Enter Rock, Paper or Scissors: ")
P2 = raw_input("Player 2: Enter Rock, Paper or Scissors: ")
if(str(P1.lower()) != "rock" and str(P1.lower()) != "paper" and str(P1.lower()) != "scissors"):
print "Must be Rock, Scissors or Paper, not: " + str(P1.lower())
elif(str((P2).lower()) != "rock" and str(P2.lower()) != "paper" and str(P2.lower()) != "scissors"):
print "Must be Rock, Scissors or Paper, not: " + str(P2.lower())
else:
sendDataToGame = self.Game(P1,P2)
def Game(self,P1,P2):
self.P1 = P1
self.P2 = P2
wantToExit = ""
while(True):
if(str(self.P1).lower() == str(self.P2).lower()):
print "You are in a tie!"
wantToExit = raw_input("Do you want to exit? yes/no: ")
if(wantToExit.lower() == "yes"):
break
else:
self.Check()
Call = RPS_Game() #instantiate
Call.Check() #calling Check function
您正在回溯性地创建更多游戏。请注意 RPS_Game.Game
调用 self.Chek()
,而 RPS_Game.Check
调用 self.Game()
.
所以每次游戏结束时,带有 sendDataToGame = self.Game(P1,P2)
的行都会创建一个新游戏。您必须退出所有游戏才能退出脚本。
你的代码中还有很多其他的东西我也会做不同的事情,所以这里有一个实现可以解决你的问题并清理一些其他的东西:
class RPS_Game(object):
# create tuples that contain all valid combinations
# this will make the comparisons easier later
ties = (('r', 'r'), ('p', 'p'), ('s', 's'))
p1_wins = (('r', 's'), ('s', 'p'), ('p', 'r'))
p2_wins = (('s', 'r'), ('p', 's'), ('r', 'p'))
# use a method to print our options for the users so we don't have to code the same
# thing twice - also notice that I'm using the python convention of lowercase names
# for functions & methods
def display_options(self, player):
print("Player {}: Press 'R' for rock, 'P' for paper, or 'S' for scissors"
.format(player)) # using string substitution to insert the player
# number appropriate on each function call
def check(self, inputs):
# Since we created the ties and wins tuples, we can now use the "in" operator
# to check for membership instead of having long and difficult to read
# string comparisons
if inputs in self.ties:
print("You tied!")
elif inputs in self.p1_wins:
print("Player 1 wins!")
elif inputs in self.p2_wins:
print("Player 2 wins!")
# if the inputs weren't in any of our tuples, we know it was invalid input
else:
print("\nInvalid input. Please try again.\n")
# return false if the input was invalid - this will be used by the caller
return False
# returning True indicates that the responses were valid
return True
def run(self):
# use a loop to start another game if the user wants to
while True:
# call our display options function, passing it the player number
self.display_options(1)
# get first player's response
p1 = raw_input("").lower()
# same things for second player
self.display_options(2)
p2 = raw_input("").lower()
# create a tuple out of our player's selections for easy membership
# checking in our tuples of valid combinations
inputs = (p1, p2)
# check our inputs both for validity and to see who wins
valid = self.check(inputs)
# if our input wasn't valid, skip the exit prompt and start a new game
# notice how the "check" function was set up to return false if
# input is not valid - now this comparison reads almost like regular
# English!
if not valid:
continue
repeat = raw_input("Play again? (Y/N)\n").lower()
# if the user entered "n" for starting another game, break out of
# the infinite loop and exit
if repeat == 'n':
break
# create the game object and run it
game = RPS_Game()
game.run()
你陷入了一些递归调用
check ->
Game ->
check ->
Game -> ...
当你在一个关卡中退出游戏时,你 return 进入链调用中的上一个关卡,这就是为什么它会多次询问你。
当变量已经是 str(...)
中的字符串时,您还可以将它们转换为字符串,这样一事无成。您还多次重复降低价格的要求,尽量避免这种情况。现在使用 return
而不是递归调用来获取函数的结果。
例如这样
class RPS_Game(object):
def ask_play(self, player):
# this function will iterate until you get a satisfactory
# input from the user
while True:
P = raw_input(player+" Enter Rock, Paper or Scissors: ").lower()
#raw_input give you a string result, to that result you can immediately call
#.lower(), that way you always work with a lower case string
if P in {"rock","paper","scissors"}:
#this is one of the best way to ask if a variable have one of several values
return P #exit the function now that you get a satisfactory input
else:
print "Must be Rock, Scissors or Paper, not:", P
def Game(self):
while True:
P1 = self.ask_play("Player 1")
P2 = self.ask_play("Player 2")
if P1 == P2:
print "You are in a tie!"
wantToExit = raw_input("Do you want to exit? yes/no: ").lower()
if wantToExit == "yes":
break
elif P1 == "rock" and P2 == "paper":
print "Player 2 win"
#complete the rest of combination
the_game = RPS_Game() #instantiate
the_game.Game() #play the game
请注意我是如何使 ask_play
尽可能通用的,详细信息由您如何使用它提供,这样您就不需要通过同时检查 2 个变量来对所有进行复杂的操作可能的组合,只需对 1 个变量执行此操作,并使用该广义函数获得所需的任意值,因为所有这些值都是以相同的方式获得的
我正在 Python 编写剪刀石头布游戏。但这是错误:
如果我玩了8次我想退出,游戏也会问我8次。
例子:我玩了5次
游戏问我:Do you want to exit? yes/no.
当我说(写)是时,游戏再次询问我,这种情况5次。
我是Python编程的初学者,我真的不明白为什么会这样。
你能帮帮我吗?
我正在 Windows 中编程并使用命令行来执行程序。 (不知道会不会影响程序的正常运行。)
这是代码。还没完:
class RPS_Game(object):
def Check(self):
P1 = raw_input("Player 1: Enter Rock, Paper or Scissors: ")
P2 = raw_input("Player 2: Enter Rock, Paper or Scissors: ")
if(str(P1.lower()) != "rock" and str(P1.lower()) != "paper" and str(P1.lower()) != "scissors"):
print "Must be Rock, Scissors or Paper, not: " + str(P1.lower())
elif(str((P2).lower()) != "rock" and str(P2.lower()) != "paper" and str(P2.lower()) != "scissors"):
print "Must be Rock, Scissors or Paper, not: " + str(P2.lower())
else:
sendDataToGame = self.Game(P1,P2)
def Game(self,P1,P2):
self.P1 = P1
self.P2 = P2
wantToExit = ""
while(True):
if(str(self.P1).lower() == str(self.P2).lower()):
print "You are in a tie!"
wantToExit = raw_input("Do you want to exit? yes/no: ")
if(wantToExit.lower() == "yes"):
break
else:
self.Check()
Call = RPS_Game() #instantiate
Call.Check() #calling Check function
您正在回溯性地创建更多游戏。请注意 RPS_Game.Game
调用 self.Chek()
,而 RPS_Game.Check
调用 self.Game()
.
所以每次游戏结束时,带有 sendDataToGame = self.Game(P1,P2)
的行都会创建一个新游戏。您必须退出所有游戏才能退出脚本。
你的代码中还有很多其他的东西我也会做不同的事情,所以这里有一个实现可以解决你的问题并清理一些其他的东西:
class RPS_Game(object):
# create tuples that contain all valid combinations
# this will make the comparisons easier later
ties = (('r', 'r'), ('p', 'p'), ('s', 's'))
p1_wins = (('r', 's'), ('s', 'p'), ('p', 'r'))
p2_wins = (('s', 'r'), ('p', 's'), ('r', 'p'))
# use a method to print our options for the users so we don't have to code the same
# thing twice - also notice that I'm using the python convention of lowercase names
# for functions & methods
def display_options(self, player):
print("Player {}: Press 'R' for rock, 'P' for paper, or 'S' for scissors"
.format(player)) # using string substitution to insert the player
# number appropriate on each function call
def check(self, inputs):
# Since we created the ties and wins tuples, we can now use the "in" operator
# to check for membership instead of having long and difficult to read
# string comparisons
if inputs in self.ties:
print("You tied!")
elif inputs in self.p1_wins:
print("Player 1 wins!")
elif inputs in self.p2_wins:
print("Player 2 wins!")
# if the inputs weren't in any of our tuples, we know it was invalid input
else:
print("\nInvalid input. Please try again.\n")
# return false if the input was invalid - this will be used by the caller
return False
# returning True indicates that the responses were valid
return True
def run(self):
# use a loop to start another game if the user wants to
while True:
# call our display options function, passing it the player number
self.display_options(1)
# get first player's response
p1 = raw_input("").lower()
# same things for second player
self.display_options(2)
p2 = raw_input("").lower()
# create a tuple out of our player's selections for easy membership
# checking in our tuples of valid combinations
inputs = (p1, p2)
# check our inputs both for validity and to see who wins
valid = self.check(inputs)
# if our input wasn't valid, skip the exit prompt and start a new game
# notice how the "check" function was set up to return false if
# input is not valid - now this comparison reads almost like regular
# English!
if not valid:
continue
repeat = raw_input("Play again? (Y/N)\n").lower()
# if the user entered "n" for starting another game, break out of
# the infinite loop and exit
if repeat == 'n':
break
# create the game object and run it
game = RPS_Game()
game.run()
你陷入了一些递归调用
check ->
Game ->
check ->
Game -> ...
当你在一个关卡中退出游戏时,你 return 进入链调用中的上一个关卡,这就是为什么它会多次询问你。
当变量已经是 str(...)
中的字符串时,您还可以将它们转换为字符串,这样一事无成。您还多次重复降低价格的要求,尽量避免这种情况。现在使用 return
而不是递归调用来获取函数的结果。
例如这样
class RPS_Game(object):
def ask_play(self, player):
# this function will iterate until you get a satisfactory
# input from the user
while True:
P = raw_input(player+" Enter Rock, Paper or Scissors: ").lower()
#raw_input give you a string result, to that result you can immediately call
#.lower(), that way you always work with a lower case string
if P in {"rock","paper","scissors"}:
#this is one of the best way to ask if a variable have one of several values
return P #exit the function now that you get a satisfactory input
else:
print "Must be Rock, Scissors or Paper, not:", P
def Game(self):
while True:
P1 = self.ask_play("Player 1")
P2 = self.ask_play("Player 2")
if P1 == P2:
print "You are in a tie!"
wantToExit = raw_input("Do you want to exit? yes/no: ").lower()
if wantToExit == "yes":
break
elif P1 == "rock" and P2 == "paper":
print "Player 2 win"
#complete the rest of combination
the_game = RPS_Game() #instantiate
the_game.Game() #play the game
请注意我是如何使 ask_play
尽可能通用的,详细信息由您如何使用它提供,这样您就不需要通过同时检查 2 个变量来对所有进行复杂的操作可能的组合,只需对 1 个变量执行此操作,并使用该广义函数获得所需的任意值,因为所有这些值都是以相同的方式获得的