gpt4 book ai didi

java - 无法垂直检测 connect 4 win

转载 作者:行者123 更新时间:2023-11-30 04:39:44 24 4
gpt4 key购买 nike

现在我有一个学校作业,我必须使用数组在没有 gui 的情况下用 java 创建一个 connect 4 游戏。到目前为止,我已经能够让游戏检测到水平四连,但我似乎无法检测到垂直四连。最初我的数组是 6x7,但我已将其更改为 5x5,只是为了测试交换数组维度的概念。为了减少困惑,我只包含了垂直检测的代码部分。

for (column = 0; column < board.length; column++) {

count_piece = 0;
max = 0;
for (row = 0; row < board.length; row++) {
if (max < count_piece) {
max = count_piece;
}
if (board[column][row] == 'X') {
count_piece++;
} else {
count_piece = 0;
}

}

}
System.out.println(max);
if (max == 4) {
System.out.println("\nYou Win!");
break;
}

如果您需要更多信息或有任何不清楚的地方,请告诉我,我很乐意提供更多信息。

编辑:这是带有倒循环的一个。

for (row = 0; row < board.length; row++) {
count_piece = 0;
max = 0;
for (column = 0; column < board.length; column++) {

if (max < count_piece) {
max = count_piece;
}
if (board[column][row] == 'X') {
count_piece++;
} else {
count_piece = 0;
}

}

}

最佳答案

如何反转循环,使内部循环更改为列而不是行?

还要让您的内部循环采用您所在的单个数组的长度。

因此,不要使用 board.length,而是使用 board[i].length

编辑

我认为你的内部循环中的逻辑是错误的......

试试这个:

if (board[row][column] == 'X') {
count_piece++;
if(count_piece == 4) {
System.out.println("you win");
return;
}
} else {
count_piece = 0;
}

这里是任意大小数组的水平和垂直检查

int count_piece = 0;

//Checking Vertical Win
for (int row = 0; row < board.length; row++) {
count_piece = 0;
for (int column = 0; column < board[row].length; column++) {

if (board[row][column] == 'X') {
count_piece++;
if (count_piece == 4) {
System.out.println("you win");
return;
}

} else {
count_piece = 0;
}


}
}

//Checking Horizontal Win
for (int column = 0; column < board.length; column++) {
count_piece = 0;
for (int row = 0; row < board[column].length; row++) {

if (board[row][column] == 'X') {
count_piece++;
if (count_piece == 4) {
System.out.println("you win");
return;
}

} else {
count_piece = 0;
}


}
}

关于java - 无法垂直检测 connect 4 win,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12592499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com