views:

62

answers:

2

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?

+4  A: 

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();
}
Jack
That is it! I was so close to this like a little bit ago, but I had an `=` in between `Game` and `game` where you wrote `private Game game;` DOH!
typoknig
+1  A: 

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.

San Jacinto