2016-10-07 7 views
1

私はPythonを実践するためのテキストベースのゲームを作っています。

python 2.7 - このタイマーオブジェクトを正しく取得する

以下は、トラップシーンのコードです。場面では、プレーヤーは穴に落ち、時間内に反応しなければ(5秒)、彼は死ぬ。タイマーを起動した後、whileループ内で入力を求めます。私は見て、このコードは何とか冗長 - 私は定義された時間が2回通過した後に起こるものを定義する - しかし、私はそれを修正する方法は本当にわからない。

def b_trap(): 
    """Trap. I want to implement a timing function here. The player will need to type the appropriate command under a given time. If he cannot make a decision in time, the player dies. Timer object!!!""" 
    def b_timeout(): 
     """If player runs out of time, this is called.""" 
     b_dead("You fall into the deep hole in the floor, and die when you\nhit the floor fifty meters down. : (") 

    print "The floor suddenly disappears behind your feet. You start to fall. What do you do? HURRY!" 

    time_to_do_stuff = Timer(5.0, b_timeout) 
    time_to_do_stuff.start() 

    while time_to_do_stuff.is_alive() is True: 
     command = raw_input(" > ") 

     if command in (bv_commands['climb'] or bv_commands['jump']): 
      time_to_do_stuff.cancel() 
      b_not_ready() 
     else: 
      print "You were saying?" 
    else: 
     b_timeout() 


このコードを実行すると、何もしていない後、b_timeout()が実行されますが、raw_input()プロンプトが残っている - 私は再び入力を求めていますが、今raw_input機能(" > ")に指定されたプロンプトなし。

私には何が欠けていますか?私はちょうどPythonを学び始めたので、初心者の間違いを許してください。

答えて

0

raw_inputは、入力が受信されるまで(新しい行/復帰を待つ)効果的にプログラムを停止するブロック機能です。

この周りの2つの方法があります。

  • 録音がraw_input前と後の時間。後者が前者の5秒未満であれば、彼らはすぐに十分に反応した。このアプローチは、プレーヤーが応答するまでプレイヤーの死を示さないという、潜在的に望ましくない動作をします。
  • 別のpythonスレッドlike thisraw_inputを同時に実行してください。
関連する問題