2012-01-10 11 views
0

私は擬似乱数を生成してユーザーに推測させるプログラムを作成しようとしています。ユーザーが間違った数を推測すると、関数の最初の部分ではなく、条件付きループの先頭に戻りたいと思います(新しい疑似乱数を生成する原因になります)。ここで私がこれまで持っているものです。Pythonで数を推測するゲームの制御ループ

def guessingGame(): 
    import random 
    n = random.random() 
    input = raw_input("Guess what integer I'm thinking of.") 
    if int(input) == n: 
     print "Correct!" 
    elif int(input) < n: 
     print "Too low." 
     guessingGame() 
    elif int(input) > n: 
     print "Too high." 
     guessingGame() 
    else: 
     print "Huh?" 
     guessingGame() 

はどのように間違って推測した後、数が変化しないように局部的に不変の擬似乱数を作ることができますか?

+4

あなたが望むことができるプログラミング言語はわかりません。 –

+3

あなたはこの質問を 'loop 'とタグ付けしました。だからあなたは答えが何であるかを知っているようだ... –

+1

BASICを除いて!勝つためのGOTO! –

答えて

1
from random import randint 

def guessingGame(): 
    n = randint(1, 10) 
    correct = False 
    while not correct: 
     raw = raw_input("Guess what integer I'm thinking of.") 
     if int(i) == n: 
      print "Correct!" 
      correct = True 
     elif int(i) < n: 
      print "Too low." 
     elif int(i) > n: 
      print "Too high." 
     else: 
      print "Huh?" 

guessingGame() 
+0

ああ、aループ。ありがとう。 – sdsgg

0

ここで行う最も簡単なことは、ここでループを使用することです。再帰はありません。

しかし、再帰を使用して設定している場合は、条件式を乱数を引数として持つ独自の関数に入れるだけで、数値を再計算せずに再帰的に呼び出すことができます。

3

ここでループすることはここでは、おそらくこれを行うには良い方法ですが、あなたのコードに非常に最小限の変更を再帰的にそれを実装する方法です。

def guessingGame(n=None): 
    if n is None: 
     import random 
     n = random.randint(1, 10) 
    input = raw_input("Guess what integer I'm thinking of.") 
    if int(input) == n: 
     print "Correct!" 
    elif int(input) < n: 
     print "Too low." 
     guessingGame(n) 
    elif int(input) > n: 
     print "Too high." 
     guessingGame(n) 
    else: 
     print "Huh?" 
     guessingGame(n) 

guessingGame()にオプションのパラメータを提供することによりあなたはあなたが望む行動を得ることができます。パラメータが提供されていない場合、それは最初の呼び出しであり、nが通話に渡された後にいつでもnをランダムに選択する必要があるため、新しいものを作成しないでください。

random()の呼び出しは、random()が0と1の間の浮動小数点数を返し、コードが期待値と整数に見えるので、randint()に置き換えられました。

0

クラスを作成し、さまざまなメソッド(別名関数)内でロジックを定義することは、最善の策かもしれません。クラスの詳細については、Checkout the Python docsをご覧ください。

from random import randint 

class GuessingGame (object): 

    n = randint(1,10) 

    def prompt_input(self): 
     input = raw_input("Guess what integer I'm thinking of: ") 
     self.validate_input(input) 

    def validate_input(self, input): 
     try: 
      input = int(input) 
      self.evaluate_input(input) 

     except ValueError: 
      print "Sorry, but you need to input an integer" 
      self.prompt_input() 

    def evaluate_input(self, input): 
     if input == self.n: 
      print "Correct!" 
     elif input < self.n: 
      print "Too low." 
      self.prompt_input() 
     elif input > self.n: 
      print "Too high." 
      self.prompt_input() 
     else: 
      print "Huh?" 
      self.prompt_input() 

GuessingGame().prompt_input() 
0

ランダムにインポートして、関数外で乱数を生成しますか? また、生成された整数の範囲を設定することもできます。 例:n = random.randint(1,max) ユーザは、

関連する問題