tags:

views:

231

answers:

2

So suppose I'm developing a chess-like program using Java's Swing. I added a MouseListener to handle user input. To make a move the user must click a valid piece and then click a valid place. What's the best way to track the 2 mouse clicks in a turn? I'm thinking in use some kind of variable to record if is the turn's first click or second.

+2  A: 

Oops, I answered too quickly. Yes, a structure that encodes a click location, looks for intervening motion events and then records the second click. There should be an initiated state, an accept state, and it should probably record a abort state (maybe a press of ESC).

msw
Thanks for the quick response.
Humberto Pinheiro
+5  A: 

You have to distinguish the two game states, using a variable is fine.. you can also think something as suggested by NomeN comment and use two different listeners by swapping them.

Your case is quite simple but in general the formalism you use to handle these things is a sort of finite state machine that describes the states of your game and how to pass from one to another.

In this case you can have some states like:

  • player 1 turn
  • player 2 turn
  • main screen
  • pause screen
  • option screen

and you decide how and when to pass from a state to another, for example

  • after player1 moved you pass to player2 turn
  • after player2 moves you go back to player1 turn
  • when game starts you go in main screen
  • if you start a new game then you go to player1 turn
  • if you press pause key while in game you go from turn to pause screen and when closed you go back to the turn that was going before pause

This is just to give you an idea, so for example your MouseListener could care about states:

enum State { TURN_P1, TURN_P2, MAIN, PAUSE, ... }
public State gameState
...

public void mouseClicked(MouseEvent e)
{
  if (gameState == TURN_P1)
  {
    ...

    if (move_is_legal and so on)
      gameState = TURN_P2;
  }
  else if (gameState == TURN_P2)
  {
    ...

    if (move_is_legal and so on)
      gameState = TURN_P1;
  }
}
Jack
Thanks Jack for the response. Using a variable to hold the status of the game seems the way to go.
Humberto Pinheiro
So _that's_ what a finite state machine is. All this time I thought it was some magical CS concept but I just worked out and used that method myself for ages without realising it.
Callum Rogers