2014-03-03 86 views
2

我目前正在为大学任务制作一个TicTacToe程序。我的董事会配备了3x3 JTextFields,每个人都有一个动作监听器。我需要做的是创建另一个类来检查错误(例如,用户将放置一个不是x或o的数字或字母),他们应该得到一个对话框,指出错误,并且他们尝试输入的JTextField将返回空白。我将如何通过try-catch-finally方法去执行错误检查?TicTacToe游戏错误检查和类

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

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

+0

错误检查是一个涉及调试会话的简单过程。 – 2014-03-03 13:35:23

+0

你似乎知道该使用什么,你是否试图实现你的想法? –

+2

我强烈建议您使用按钮而不是文本框。然后使用一个字段变量,你可以自动填充它是X转还是O转。至于第二课,你需要参考第一课。你可以做的是给它一个类变量,如'logic.game = game'。然后你可以在逻辑类的任何地方使用logic.game。 – TheOneWhoPrograms

回答

0

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

然后,GameGUI类将有一个GameLogic类型的实例变量,该类型在创建GameGUI类型的对象时被初始化。按照我的想法,我会让GameLogic用2D字符组代表棋盘状态。 GameGUI将在那里将用户的输入传递给GameLogic,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将作为JTextField中的二维数组,而不是作为单独的实例变量来反映在GameLogic类的代表性。如果您使用JButton类而不是JTextField,并且用户在单击按钮上获取他正在玩的角色(如果轮到他并且此按钮之前尚未使用过),则还可以避免所有验证。