开发者

Separate thread for Java game logic

When I have made simple single thread games I implemented the game logic in much the same way that the increasingly famous Space Invaders tutorial does as shown below:

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.
}

Now I want to try and run my logic on a separate thread but I am having problems. My game logic is in a separate class file which looks like this:

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.
    }

}

... And my main method looks like this:

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();

}

How do I properly call the logic() method on the instance of my game?


you can just pass your game instance by using a constructor, or a setter like in

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();
}


y Java is REALLY rusty, so defer to the other users if there is a discrepancy.

What you have looks ok to me. When you call start(), a new thread context is created and calls run(). In run(), you are calling the function you want.

What you are missing is that the thread has no knowledge of the game. My personal preference would be to implement a thread inside game that puts the logic on its own thread that is a member of class game.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜