2010-09-06 89 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()中,你正在调用你想要的函数。

你缺少的是线程没有游戏的知识。我个人的偏好是在游戏中实现一个线程,将逻辑放在自己的线程上,这是线程游戏的一员。