2017-02-02 4 views
0

私は、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 
+0

なぜ、 ) 'を一度読み込むと、P1.lower()を何度も書き続ける必要はありませんか? – Barmar

+0

これはどのように動作するのかわかりません。それがネクタイでなければ勝者を決してチェックしないので、whileループは永遠に繰り返されます。 – Barmar

答えて

2

あなたは厄介なゲームをたくさん作成しています。 RPS_Game.Gameself.Chek()RPS_Game.Checkself.Game()となります。

ゲームが終了するたびに、​​という行が新しいゲームを作成します。スクリプトを終了するには、すべてのゲームを終了する必要があります。

あなたはので、ここであなたの問題を修正し、いくつかの他のもののクリーンアップの実装ですが、私も違っただろうあなたのコード内の他の多くのものを持っている:

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() 
+0

彼は終了するときに 'self.Check()'を呼び出さない。 – Barmar

+0

@Barmarしかし、彼がいくつかのゲームをプレイして終了する前に、スタック上のすべてのゲームを終了する必要があります。 – skrrgwasme

+0

私はRPS_Game.Gameのif/else文に改行を入れました これで私はスクリプトを終了できます –

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つの変数に対してそれを行い、その一般化された関数を使用して、すべてが同じように取得されるので、値を得ることができます。

関連する問題