TicTacToe游戏错误检查和课程

时间:2014-03-03 13:33:02

标签: java swing class

我目前正在为大学的作业制作TicTacToe课程。我的主板配有3x3 JTextFields,每个都有一个动作监听器。我需要做的是创建另一个将检查错误的类(例如,用户将放置一个非x或o的数字或字母)他们应该得到一个对话框,说明错误,他们试图输入的JTextField将返回空白。我将如何通过try-catch-finally方法实现错误检查?

另一个问题,我有一个GameGUI类,我也想拥有一个GameLogic类。如果游戏获胜,如何从GameLogic查看?在我的GameLogic中,我会有类似

的内容

如果j1,j2和j3都是x或o,则显示对话框“x player wins”。

1 个答案:

答案 0 :(得分:0)

我将尝试回答关于一般棋盘游戏的问题。你的面向对象思维分裂成不同的类是正确的。我通常做的是我让GameLogic包含我对游戏的逻辑和验证,以及确定游戏是否结束等等。

GameGUI类将具有GameLogic类型的实例变量,该变量在创建GameGUI类型的对象时初始化。按照我的想法,我会让GameLogic用2D阵列字符表示电路板状态。 GameGUI将用于将用户的输入转发给GameLogic,以确定游戏是否结束。 GameLogic应该抛出你要澄清的类型的异常,然后GameGUI应该尝试使用JText字段中用户的输入文本更新电路板,从GameLogic中捕获错误(如果有的话),然后重新绘制根据获得的输入向用户显示的GUI。我将在下面举例说明我的观点,虽然我不会提供TicTacToe游戏的实际实现,但你可以自己轻松完成。

public class GameLogic {
    ....
    char[][]board;
    public GameLogic() {
       //initialize the board representation for game
    }
    public boolean gameOver() {
       //determine if the game is over by checking the board 2D array
       // 3 xs or os in a row, column, or diagonal should determine the game is over or if there are no more moves
    }
    public void move(char character, int x, int y) {
       //update a certain position with a character should throw an Exception if the character is invalid or if the the character is valid but it's not the character that the user owns player1 plays with x for example but puts o.
      //should also have the logic for the turns
    }
    ...
}

public class GameGUI {
    .....
    GameLogic engine;
    public GameGUI() {
        engine = new GameLogic();   
    }

    public void actionPerformed(ActionEvent e) {
        // here you would get the co-ordinates of the clicked JTextButton
        // then call the method move on the engine instance
        try {
            engine.move(character, x, y);
        } catch(Exception e) {
            //display the validation for the error that happened
        }
        //repaint the representation from the engine to be displayed on the GUI Frame that you are using
    }
    ...
}

还有一件事是我会将JTextFields声明为JTextFields的2D数组,而不是单独的实例变量来镜像GameLogic类中的表示。如果你使用JButton类而不是JTextField,你也可以一起避免验证,如果轮到他并且之前没有使用过该按钮,那么用户就可以获得他在点击按钮上玩的角色。

相关问题