【问题标题】:TicTacToe game error checking and classesTicTacToe 游戏错误检查和类
【发布时间】:2014-03-03 13:33:01
【问题描述】:

我目前正在为大学作业制作井字游戏。我用 3x3 JTextFields 布置了我的电路板,每个都附加了一个动作侦听器。我需要做的是创建另一个类来检查错误(例如,用户将输入不是 x 或 o 的数字或字母)他们应该得到一个对话框,说明错误并且他们尝试输入的 JTextField 将返回为空白。我将如何通过 try - catch - finally 方法来实现错误检查?

另一个问题,我有一个 GameGUI 类,我也想要一个 GameLogic 类。我如何从 GameLogic 检查游戏是否已赢?在我的 GameLogic 中,我会有类似

如果 j1、j2 和 j3 都是 x 或 o,则显示对话框“x 玩家获胜”。

【问题讨论】:

  • 错误检查是一个让您参与调试会话的简单过程。
  • 你好像知道用什么了,有没有尝试去实现你的想法?
  • 我强烈建议您使用按钮而不是文本字段。然后使用字段变量,您可以自动填充是 X 转还是 O 转。至于第二类,您需要参考第一类。你可以做的是给它一个类变量,比如logic.game = game。然后你可以在逻辑类的任何地方使用 logic.game。
  • @TheOneWhoPrograms 根据教授的要求,遗憾的是我们不允许使用按钮,如果可以的话,这对我来说似乎更容易。 JordanD 是也不是,我只熟悉一些错误检查,你能指出我使用 check-catch-finally 的正确方向吗?
  • 我认为一些非常简单的 If Else 检查就足够了,而不必在这里处理任何类型的异常。 `if (turn.equals(textfield.text().toString()){do stuff}else{tell them its wrong} 在另一个说明中。如果您的教授说没有按钮,您可以利用将标签视为按钮的优势。它们是不完全是按钮,但可以视为一个。

标签: java swing class


【解决方案1】:

我将尝试回答有关一般棋盘游戏的问题。您将面向对象拆分为不同类的想法是正确的。我通常做的是我有 GameLogic 包含我的游戏逻辑和验证,以及确定游戏是否结束等等。

GameGUI 类将拥有一个 GameLogic 类型的实例变量,该变量在创建 GameGUI 类型的对象时被初始化。在我的思维方式中,我会让 GameLogic 用 2D 字符数组来表示棋盘状态。 GameGUI 将只是将用户的输入中继到 GameLogic,后者确定游戏是否结束。 GameLogic 应该抛出您想要澄清的类型的异常,然后 GameGUI 应该尝试使用 JText 字段中用户的输入文本更新板,从 GameLogic(如果有)捕获错误,然后重新绘制根据获得的输入向用户显示的 GUI。我将在下面给出一个示例来阐明我的观点,虽然我不会提供井字游戏的实际实现,但您可以自己轻松完成。

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 并且如果轮到他并且之前未使用过该按钮,则用户可以在单击的按钮上获得他正在玩的角色,您也可以一起避免验证。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多