java - Java Connect4 游戏。我想检查列是否已满
问题描述
我正在尝试检查玩家想要投入硬币的栏是否已满。当我把柱子装满并且我把另一个硬币放在那里时,它超出了界限。我如何检查它是否已满并且没有超出债券。
for(int o = rows- 1;o>= 0; o--) {
if (boards[o][nextColumn]=="- " ) {
boards[o][nextColumn] = nextSymbol + " " ;
break;
}
if (fullColumn > rows ) {
System.out.println("The column is full!");
break;
}
}
解决方案
您收到 IndexOutOfBoundsException 是因为当您初始化循环时,值为g
0。
for(int g=0;g<rows;g++)
然后,当您在循环的同一迭代中时,您正在检查下一个单元格是否包含与当前单元格相同的符号,但您是通过递减来完成的g
。
boards[g][s].equals(boards[g-1][s+1])
如果 的值g
从零开始,则 的值为g-1
-1,这会产生错误,因为根据定义,您的数组从索引 0 开始。
当你检查你的对角线时,你不能只用一种方法——对角线是有方向的。不考虑这种方向性是导致您的测试失败的原因。
拿一张纸画你的板子
Diagonal 1
3 - - - o
2 - - o -
1 - o - -
0 o - - -
0 1 2 3
Diagonal 2
3 o - - -
2 - o - -
1 - - o -
0 - - - o
0 1 2 3
在对角线 1 的情况下,您需要同时递增g
和递增s
,但由于我们知道g == s
对于第一条对角线上的每个点,我们只需要一个变量。
for(int g = 0; g < 4;g++)
{
if(boards[g][g].equals(boards[g + 1][g + 1]))
{
// still matching. I have no idea how your code is tracking
// matches, so you'll have to adapt this on your own
}
else
{
// no match, no need to continue the loop
// break; or exit however you want
}
}
对于对角线 2,就像我们知道g == s
对角线 1 的所有点一样,我们知道g == 3 - s
,所以你可以
for(int s = 0; s < 4;s++)
{
if(boards[(3 - s)][s].equals(boards[2 - s][s + 1]))
{
// still matching. I have no idea how your code is tracking
// matches, so you'll have to adapt this on your own
}
else
{
// no match, no need to continue the loop
// break; or exit however you want
}
}
每当您无法将头绕在某件事上时,请画一幅画并在纸上工作,直到您了解自己在处理什么。
推荐阅读
- javascript - 为什么 DayJs 会导致网站冻结而不加载?
- amazon-web-services - AWS Lightsail 无法为 Let'sEncrypt 证书更新 Route53
- javascript - JS 中的 for...of 是否传递值或引用?
- python - 如何将“百分比”文本标签添加到 Altair 标准化堆叠条形图?
- c# - DisplayAttribute ResourceType 找不到资源
- octave - 同时显示编辑器和输出
- android - 如何在 React Native 中将整个选择更改为单个选择?
- r - 在堆积条形图中构建分组条形图
- android - 如何使用任何形式的 android 视频捕获来安排每帧回调
- javascript - 将 csv 数据合并到 html javascript