我会尽量回答关于一般棋盘游戏的问题。你面向对象的思想分裂成不同的类是正确的。我通常所做的是我拥有包含我的逻辑和游戏验证的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,并且用户在单击按钮上获取他正在玩的角色(如果轮到他并且此按钮之前尚未使用过),则还可以避免所有验证。
错误检查是一个涉及调试会话的简单过程。 – 2014-03-03 13:35:23
你似乎知道该使用什么,你是否试图实现你的想法? –
我强烈建议您使用按钮而不是文本框。然后使用一个字段变量,你可以自动填充它是X转还是O转。至于第二课,你需要参考第一课。你可以做的是给它一个类变量,如'logic.game = game'。然后你可以在逻辑类的任何地方使用logic.game。 – TheOneWhoPrograms