程序退出

时间:2017-02-02 00:25:25

标签: python recursion control-flow

我用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

2 个答案:

答案 0 :(得分:2)

你不情愿地制作更多游戏。请注意,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() 

答案 1 :(得分:0)

你陷入了一些递归的呼唤

check ->
    Game ->
        check ->
           Game -> ...

当您在一个级别退出游戏时,您将返回到链式调用中的上一级别,这就是为什么它会多次询问您。

当你的变量已经是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个变量做,并使用该通用函数得到你想要的值,因为所有这些都是以相同的方式获得