Java 2D step-by-step programming: handle 2 mouse clicks on a player

So, suppose I am developing a chess program using Java Swing. I added MouseListener to handle user input. To make a move, the user must click on the real part, and then click on the valid location. What is the best way to track 2 clicks in a queue? I am thinking of using some kind of variable for recording if this is the first click or the second rotation.

+3
source share
2 answers

You must distinguish the two states of the game using the variable in order. You can also think of something suggested by the NomeN comment and use two different listeners to replace them.

Your business is quite simple, but in general, the formalism that you use to process these things is a kind of finite state machine that describes the state of your game and how to move from one to another.

In this case, you can have several states, for example:

  • player 1 turn
  • player 2 lines
  • main screen
  • pause screen
  • settings screen

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

  • after player1 moves you to player2.
  • after player2 moves you back to player1.
  • When the game starts, you go to the main screen.
  • , player1
  • , , , .

, , , , MouseListener :

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;
  }
}
+5

, . , , , , . , , , , (, ESC).

+2

Source: https://habr.com/ru/post/1736792/


All Articles