2017-10-28 421 views
2

我是python的初學者,我在做一個簡單的python遊戲。我試圖解決以下錯誤RuntimeError: threads can only be started oncePython:RuntimeError:線程只能啓動一次

我試圖.cancel()計時器,但已經似乎沒有工作,我已經做了一個if語句,看看計時器.is_alive執行前。控制檯拋出錯誤送行ball_char = play_timer.start()

def playball(state): 
batbox = [["@", "@", "@", "@"], ["@", "#", "#", "#", "@"], ["@", "#", "#", "#", "@"], ["@", "#", "#", "#", "@"], ["@", "@", "@", "@"]] 
play = "playing" 
play_timer = Timer(1.0, pitch(batbox)) 
end_timer = Timer(6.0, pitch_end(play)) 
play_timer.cancel() 
end_timer.cancel() 
pstate = "idle" 
inning = 1 
outs = 0 
pscore =0 
cscore = 0 
strikes = 0 
ball_row = 0 
ball_col = 0 
ball_char = "." 
while play == "playing": 
    batbox = [["@", "@", "@", "@"], ["@", "#", "#", "#", "@"], ["@", "#", "#", "#", "@"], ["@", "#", "#", "#", "@"], ["@", "@", "@", "@"]] 
    os.system('cls') # on windows 
    os.system('clear') # on linux/os x 
    # Playing the game 
    print "Press enter to start/hit the pitch" 
    print_grid(batbox) 
    input = raw_input("") 
    pstate = "hitting" 
    # Hitting 
    if pstate == "hitting": 
     ball_row = random_row(batbox) 
     ball_col = random_col(batbox) 
     end_timer.start() 
     while pstate == "hitting": 
      batbox[ball_row][ball_col] = ball_char 
      if play_timer.is_alive(): 
       play_timer.cancel() 
      else: 
       ball_char = play_timer.start() 
else: 
    play_timer.cancel() 
    end_timer.cancel() 
    state = "mainmenue" 
    return state 
+0

意思就是它所說的。如果您想啓動多個線程,請創建多個對象。一旦你啓動了一個線程,你不能再次啓動它,即使它在過渡時期被關閉或退出,也要創建一個新的Timer對象。這裏有什麼祕密? –

+1

順便說一句,一般來說,一個[mcve]將會刪除所有與玩遊戲有關的位,並且只會關注*提供儘可能最短的代碼,以演示您需要幫助的定時器/線程的行爲。 (此外,適當的MCVE將成爲任何人都可以複製和粘貼的代碼,無需任何其他設置或框架(導入,設置代碼等)即可自行查看問題;這不會按原樣運行,並且所以在該定義之外)。 –

回答

2

documentation for Threading.Thread(其中定時器是一個子類)規定:

start() Start the thread’s activity.

It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.

This method will raise a RuntimeError if called more than once on the same thread object.

即使你取消線程(或定時器),你仍然不能打電話重新開始。你需要創建一個新的線程/計時器對象,或者它是一個錯誤。

+0

所以,我可以重新定義'play_timer = Timer(1.0,pitch(batbox))'?或者我必須製作一個全新的計時器? – Handge

+0

@Handge是的,該代碼會創建一個可以使用的新計時器。 – mbrig