为Tic Tac Toe Java GUI创建一个布尔值,以告知玩家是否获胜

时间:2014-08-16 23:28:39

标签: java boolean logic

我是编程新手,并且一直在努力制作一个GUI tic tac toe游戏。为了显示我的一个愚蠢的程序,其中点击了四个按钮,它将打印“X' X'或者'。我能够改变顺便说一下X' X'和' Y'对于我的GUI游戏,只要点击一个按钮。但是,我一直致力于创建一个char数组来检测玩家是否赢了。

 class Board extends JPanel{

    // char[][] cells = new char[2][2];
    //boolean won(char token)....?
    //any clue to construct a boolean to tell if cells[0][0] === cels[0][1]?

    private char token = ' ';
    char turn = 'O';
    char getToken(){
        return token;
    }

    void setToken(char token){
        this.token = token;
    }


    JButton b[] = new JButton[4];

    public Board(){
        setLayout(new GridLayout(2,2,0,0));
        for(int i = 0 ; i < 4; i ++){
            b[i] = new JButton();
            add(b[i]);
        }
        listener();

    }
    void listener(){

            for(int i = 0; i < 4; i ++){
            b[i].addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                turn = (turn == 'X') ? 'O': 'X';

                System.out.println("Button Clicked" + turn);
          //add if(won(turn))....?

            }
        });
    }

1 个答案:

答案 0 :(得分:0)

通过代码,我猜你正在创建一个带按钮和字符矩阵的3X3方块。 因此,要检查玩家是否获胜,您需要检查

[0][0] == [0][1] == [0][2] OR
[1][0] == [1][1] == [1][2] OR
[2][0] == [2][1] == [2][2]

[0][0] == [1][0] == [2][0] OR
[0][1] == [1][1] == [2][1] OR
[0][2] == [1][2] == [2][2]

对角线

[0][0] == [1][1] == [2][2] OR
[0][2] == [1][1] == [2][0]

PS:OR = ||