我如何让我的tictactoe游戏成为平局?

时间:2016-04-19 00:51:29

标签: java javafx game-physics tic-tac-toe

所以我有一个完全可操作的tic tac toe游戏,但是如果没有人赢得游戏就停止因为我没有引入领带测量或对象。所以我决定在我的if(hasWinner)之后添加一个else:

        public class TicTacToePractice extends Application{
        Pane gameboard = new Pane();
        Label displayPlayer = new Label("Player A");
        char winningChar = '?';
        boolean hasWinner = false;
        boolean isPlayerA = true;
        Button[] btnPosition = new Button[16];

@Override
public void start(Stage stage){
    for(int i = 0; i < 16; i++){
    btnPosition[i] = new Button();
    btnPosition[i].setLayoutX(i % 4 * 100);
    btnPosition[i].setLayoutY(i / 4 * 100);
    btnPosition[i].setPrefSize(100, 100);
    final int pos = i;
    btnPosition[i].setOnAction(e->{setClick(pos);});
    gameboard.getChildren().add(btnPosition[i]);
    }
    displayPlayer.setLayoutX(170);
    displayPlayer.setLayoutY(420);
    gameboard.getChildren().add(displayPlayer);

    Scene scene = new Scene(gameboard, 400, 450);
    stage.setScene(scene);
    stage.show();
}

public void setClick(int i){
   btnPosition[i].setFont(Font.font(30));
   if(isPlayerA){
       btnPosition[i].setText("O");
       isPlayerA = false;
       displayPlayer.setText("Player A");
   }
   else{
       btnPosition[i].setText("X");
       isPlayerA = true;
       displayPlayer.setText("Player B");
   }
   btnPosition[i].setDisable(true);
   findWinner();
}

public void findWinner(){
    checkRows();
    checkColumns();
    checkDiagonals();
    if(hasWinner){
    for(int i = 0; i < 16; i++){
        btnPosition[i].setDisable(true);
    }
    if(winningChar == 'O'){
        displayPlayer.setText("Player A has WON!");
    }
        else{
        displayPlayer.setText("Player B has WON!");
    }
  }
    else{ // i added this else to find out if i could make it into a tie... 
          //but after someone clicks one button it says its a tie but the game keeps playing
      displayPlayer.setText("It's a Tie!");
   }
}

这是checkRows()的一种方法,如果它有所不同:

    public void checkRows(){
    if(btnPosition[0].getText().equals(btnPosition[1].getText())
            && btnPosition[1].getText().equals(btnPosition[2].getText())
            && btnPosition[2].getText().equals(btnPosition[3].getText())
            && !btnPosition[3].getText().isEmpty()){
            hasWinner = true;
            setWinner();
    }
    else  if(btnPosition[3].getText().equals(btnPosition[4].getText())
            && btnPosition[4].getText().equals(btnPosition[5].getText())
            && btnPosition[5].getText().equals(btnPosition[6].getText())
            && !btnPosition[6].getText().isEmpty()){
            hasWinner = true;
            setWinner();
    }
等等......所以任何人都可以帮助找到一种方法让我的游戏让它说如果没有人获胜并且所有16个方格都被填满,它最终会成为一个平局?我正在寻找最简单的解决方案。哦,如果你在setWinner()中想知道什么,那就是以下内容:

          public void setWinner(){
    if(!isPlayerA){
        winningChar = 'O';
    }
    else{
        winningChar = 'X';
    }
}  

0 个答案:

没有答案