1

I would like to know better way to implement alternatly switching of moves between computer and human in small game. Computer plays first, than human plays by clicking some of the buttons, again computer, again human etc.

frame.computerPlaysRandom();
while(!frame.end)
{
//if(frame.alreadyExecuted)
// {  
frame.computerPlaysRandom();

// }
// frame.computerPlaysRandom();
}

I thought of putting boolean variable alreadyExecuted at the end of humanPlays method, but it doesnt work.

public void computerPlaysRandom()
{
  ......
  if(activeColour == RED)
  {
    .....
  }
     activeColour = YELLOW;       
}

I dont like this way first of all it looks unnatural like human and computer play at exactly same time. And another that it is constantly looping.

I tried my best to explain, please give me suggestion of better way to do this.

mike_cus
  • 67
  • 1
  • 10
  • 2
    A **game model** should keep track of whose play it is. Rather than making a 'game loop' as above (the loop will tend to block the Event Dispatch Thread), ensure the game instead reacts to events in the GUI. – Andrew Thompson Oct 18 '17 at 03:05

1 Answers1

4

As @ Andrew Thompson comments, "A game model should keep track of whose play it is." A simple MVC example game is examined here. In this more complex turn-based game, a player moves to flee advancing enemies when a key is pressed. The key handler, seen here, invokes the game model's move() method with the given Key:

game.move(k.getMove());

The game model's move() method updates the player's position and moves the enemies accordingly. The model then fires an update event in a call to moveBots(). Each listening view then renders its portion of the new game state. For example, RCView draws the new player/enemy positions, and other views update the score and status displays.

If your model's game logic is too complex it may slow the event dispatch thread. If so, run the model in the background of a SwingWorker.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • 1
    What I was crudely trying to communicate, but with bucketfulls more detail and actual code to back it up. Thanks TG! – Andrew Thompson Oct 18 '17 at 11:15
  • @trashgod thanks for MVC suggestion. anyway, I dont really get not having while loop for example if both players are robots, how to implement game flow without loop. I can manage it when at least one player is human because I will than have control by following actionPerformed method(after player press button) ? – mike_cus Oct 20 '17 at 18:30
  • 1
    The game uses a `javax.swing.Timer` to pace serial calls to the model; press `A` to toggle animation when using the mouse to see the effect – trashgod Oct 20 '17 at 23:05