2015-12-21 38 views
0

我正在python中構建一個遊戲,並且我想創建一個事件偵聽器來檢查主角色的hp是小於還是等於0,然後通過函數執行遊戲。在其他語言(vb.net)中,我通過創建一個不斷循環if語句直到條件滿足的新線程來實現此目的,然後通過代碼運行遊戲,然後關閉自身。你如何在python中創建/啓動/關閉線程?另外,有沒有更好的方法可以坐在我面前?你如何在Python中創建一個新的線程?

+0

你可以通過這樣做來獲得一個Race Condition。 –

+0

什麼是競賽條件? –

+0

沒關係。當遊戲變得複雜時,仍然認爲這是一個糟糕的主意。 –

回答

2
from threading import Thread 

def my_function(): 
    while True: 
     if player.lives < 5: 
      do_stuff() 

Thread(my_function).start() 

然而大部分的遊戲都遵循幀循環規律發展的時代,具有以下結構:

def my_game(): 
    should_continue = False 
    while should_continue: 
     should_continue = update_logic() 
     update_graphics() 

你update_logic和update_graphics定義什麼是你和圖形庫您正在使用(由於您使用的文字,你的函數將只打印您的控制檯文本),但邏輯的一些例子會是這樣的:

def update_logic(): 
    if player.lives < 5: 
     return False 
    # these are just examples, perhaps not valid in your game 
    player.xdirection = 0 
    player.ydirection = 0 
    player.speed = 0 
    player.hitting = False 
    if player.damage_received_timer > 0: 
     player.damage_received_timer -= 1 
    if right_key_pressed: 
     player.xdirection = 1 
    if left_key_pressed: 
     player.xdirection = -1 
    if up_key_pressed: 
     player.ydirection = -1 
    if down_key_pressed: 
     player.ydirection = +1 
    if player.ydirection or player.xdirection: 
     player.speed = 20 
    if space_key_pressed: 
     player.hitting = True 
    # bla bla bla more logic 
    return True 

這確實沒有如果發生多個事件,那麼使用線程和使用線程是最糟糕的做法。然而在你的文字遊戲中,可能沒有太多元素參與其中,所以不太可能出現競爭狀況。不過要小心。我總是喜歡這些循環而不是線程。

+0

非常感謝你 –

+0

請** rtfm **。這是一個壞主意。像Clickteam Fusion和YoYo GameMaker這樣的遊戲引擎,最好使用幀循環迭代。 –

+0

so ...是threading.thread一個通用對象嗎? (我的意思是它存在於所有現代語言中的某種相似形式?) –

相關問題