【发布时间】:2016-05-15 06:41:34
【问题描述】:
所以我正在研究井字游戏程序,并且我正在研究一种可以检测玩家是否获胜的方法。
游戏的程序如下:游戏板是一个包含 9 个整数的 int 数组。玩家 1 将能够用“1”填充数组的指定部分,玩家 2 用“2”填充数组的指定部分。
现在,在我检查胜利的方法中,我使用了一个相当长且令人费解的 if/else 语句,但最终没有编译错误并且程序运行正确,但是当某些空格是以触发胜利条件的方式填充,我的方法没有打印它应该打印的行。
例如:
run:
Player 1, please enter the number of the square that you want to mark (1 - 9)
1
[1, 0, 0, 0, 0, 0, 0, 0, 0]
Player 2, please enter the number of the square that you want to mark (1 - 9)
6
[1, 0, 0, 0, 0, 2, 0, 0, 0]
Player 1, please enter the number of the square that you want to mark (1 - 9)
2
[1, 1, 0, 0, 0, 2, 0, 0, 0]
Player 2, please enter the number of the square that you want to mark (1 - 9)
8
[1, 1, 0, 0, 0, 2, 0, 2, 0]
Player 1, please enter the number of the square that you want to mark (1 - 9)
3
[1, 1, 1, 0, 0, 2, 0, 2, 0]
Player 2, please enter the number of the square that you want to mark (1 - 9)
所以你可以在最后一行看到,数组中的前 3 个整数已被玩家 1 填充,这应该会触发消息说玩家 1 赢了,但没有出现这样的消息。
这里是应该获得胜利条件的方法:
public void checkWin() {
int row1 = board[0] + board[1] + board[2];
int row2 = board[3] + board[4] + board[5];
int row3 = board[6] + board[7] + board[8];
int column1 = board[0] + board[3] + board[6];
int column2 = board[1] + board[4] + board[7];
int column3 = board[2] + board[5] + board[8];
int cross1 = board[0] + board[4] + board[8];
int cross2 = board[2] + board[4] + board[6];
int square0 = board[0];
int square1 = board[1];
int square2 = board[2];
int square3 = board[3];
int square4 = board[4];
int square5 = board[5];
int square6 = board[6];
int square7 = board[7];
int square8 = board[8];
if (row1 == 3 | row1 == 6 | row2 == 3 | row2 == 6 | row3 == 3 | row3 == 6|
column1 == 3 | column1 == 6 | column2 == 3 | column2 == 6 | column3 == 3 | column3 == 6|
cross1 == 3 | cross1 == 6 | cross2 == 3 | cross2 == 6) {
} else if ((square0 == 1 && square1 == 1 && square2 == 1) ||
(square3 == 1 && square4 == 1 && square5 == 1) ||
(square6 == 1 && square7 == 1 && square8 == 1) ||
(square0 == 1 && square3 == 1 && square6 == 1) ||
(square1 == 1 && square4 == 1 && square7 == 1) ||
(square2 == 1 && square5 == 1 && square8 == 1) ||
(square0 == 1 && square4 == 1 && square8 == 1) ||
(square2 == 1 && square4 == 1 && square6 == 1)) {
System.out.println("Player 1 has won this game!");
} else if ((square0 == 2 && square1 == 2 && square2 == 2) ||
(square3 == 2 && square4 == 2 && square5 == 2) ||
(square6 == 2 && square7 == 2 && square8 == 2) ||
(square0 == 2 && square3 == 2 && square6 == 2) ||
(square1 == 2 && square4 == 2 && square7 == 2) ||
(square2 == 2 && square5 == 2 && square8 == 2) ||
(square0 == 2 && square4 == 2 && square8 == 2) ||
(square2 == 2 && square4 == 2 && square6 == 2)) {
System.out.println("Player 2 has won this game!");
}
}
我知道这很复杂,但我无法找到一种方法来缩短它,同时仍然说明该方法应该如何工作。
如果有人能指出我遗漏了什么或做错了什么,我将不胜感激。
谢谢大家!
【问题讨论】:
-
考虑使用数组让生活更美好。
-
空白似乎被触发了,因为
row1 == 3 -
您使用的是
|而不是||? -
哇哦,我学到了一些新东西。但很高兴我一直使用
||更适合短路...
标签: java arrays if-statement