Kuba K
Kuba K

Reputation: 33

JavaFX button click and next move

I would do a game: tic tac toe with JavaFX. I created board 3x3 with buttons The first player click one of them and selected button text change to "O" or "X" I would do a loop,something like this:

while(true){
  player1.move("x");
  player2.move("O");
}

In move():

public void move(String a){
      board[0][0].setOnAction(new EventHandler<ActionEvent>() {
           @Override
           public void handle(ActionEvent event) {
                   board[0][0].setText(a);
                   board[0][0].setDisable(true);
               }
           });
       board[0][1].setOnAction(new EventHandler<ActionEvent>() {
           @Override
           public void handle(ActionEvent event) {
                   board[0][1].setText(a);
                   board[0][1].setDisable(true);
               }
           });
          [...]
}

But the application doesn't work (because of loop) I don't know how to do that first player one have a move and when he choose and click to button, the player 2 have a next move.

Upvotes: 0

Views: 945

Answers (2)

ShellCode
ShellCode

Reputation: 1172

You don't need any main game loop, here is the logic you need :

int player = 0;
String [] symbol = {"X", "O"};

for(int i = 0; i < 3; i++) {
    for(int j = 0; j < 3; j++) {
        board[i][j].setOnAction(action -> {
            plansza[i][j].setText(symbol[player]);

            checkIfPlayerWon();

            player = (player + 1) % 2;
        });
    }
}

Adjust it to your needs

Upvotes: 0

FFdeveloper
FFdeveloper

Reputation: 241

I don't know how to do that first player one have a move and when he choose and click to button, the player 2 have a next move.

You have to add a game manager that controls the game. You have to manage turns of the game and check, for each turn, if one of the player wins. And, of course, other things like move.

Upvotes: 1

Related Questions