2010-09-06 86 views
0

當我做了簡單的單個線程的遊戲我實現了遊戲邏輯在幾乎相同的方式將越來越多地著名Space Invaders tutorial做如下圖所示:單獨的線程的Java遊戲邏輯

public static void main(String[] args) { //This is the COMPLETE main method 
    Game game = new Game(); // Creates a new game. 
    game.gameLogic(); // Starts running game logic. 
} 

現在我想嘗試在一個單獨的線程上運行我的邏輯,但我遇到了問題。我的遊戲邏輯是在一個單獨的類文件看起來像這樣:

public class AddLogic implements Runnable { 

    public void logic(){ 
     //game logic goes here and repaint() is called at end 
    } 

    public void paintComponent(Graphics g){ 
     //paints stuff 
    } 

    public void run(){ 
     game.logic(); //I know this isn't right, but I cannot figure out what to put here. Since run() must contain no arguments I don't know how to pass the instance of my game to it neatly. 
    } 

}

...而我的主要方法是這樣的:

public static void main(String[] args) { //This is the COMPLETE main method 
    Game game = new Game(); // Creates a new game. 
    Thread logic = new Thread(new AddLogic(), "logic"); //I don't think this is right either 
    logic.start(); 

} 

如何正確撥打我的遊戲實例的邏輯()方法?

回答

4

你可以通過構造函數或二傳手就像

public GameThread extends Thread { 
    private Game game; 

    GameThread(Game game) { 
    this.game = game; 
    } 

    public void run() { 
    game.logic(); 
    } 
} 

public static void main(String[] args) { 
    GameThread thread = new GameThread(new Game()); 
    thread.start(); 
} 
+0

就是這樣!我和前一陣子非常接近,但是在'Game'和'game'之間有一個'=',在那裏你寫了'private game game;'DOH! – ubiquibacon 2010-09-06 02:33:09

1

ŸJava是真的生鏽通過你的遊戲實例,因此推遲到其他用戶如果有差異。

你對我有什麼好看的。當你調用start()時,會創建一個新的線程上下文並調用run()。在run()中,你正在調用你想要的函數。

你缺少的是線程沒有遊戲的知識。我個人的偏好是在遊戲中實現一個線程,將邏輯放在自己的線程上,這是線程遊戲的一員。