java示例代码未按预期执行
这是算法(不工作),请告诉我错误在哪里
谢谢
private void checkSouth(Location point, int player) {
//Loop through everything south
boolean isthereAnOppositePlayer=false;
int oppositePlayer=0;
//Set opposite player
if (player==1) {
oppositePlayer=2;
}else{
oppositePlayer=1;
}
for (int i = point.getVertical(); i < 8; i++) {
//Create a location point with the current location being compared
MyLocation locationBeingChecked= new MyLocation();
locationBeingChecked.setHorizontal(point.getHorizontal());
locationBeingChecked.setVertical(i);
int value = board[locationBeingChecked.getVertical()][locationBeingChecked.getHorizontal()];
//If the first checked is the opposite player
if (value==oppositePlayer) {
//Then potential to evaluate more
isthereAnOppositePlayer=true;
}
//If it isn't an opposite player, then break
if(!isthereAnOppositePlayer && value!=0){
break;
}
//If another of the player's piece found or 0, then end
if (isthereAnOppositePlayer && value==player || isthereAnOppositePlayer && value==0) {
break;
//end
}
//Add to number of players to flip
if(isthereAnOppositePlayer && value==oppositePlayer && value!=0){
//add to array
addToPiecesToTurn(locationBeingChecked);
}
}
}
# 1 楼答案
为什么不使用2d阵列
每个单元格将包含一个枚举:空、PLAYER_1、PLAYER_2
然后,为了遍历单元格,只需对每个方向使用循环
例如,单击一个单元格时,右边的复选框为:
从上到下的检查将是:
# 2 楼答案
看起来旋转回到另一个玩家的位置与第一步中旋转的位置完全相同。我猜由
addToPiecesToTurn
填充的数组在每次移动之间可能没有被清除,所以之前的所有位置都仍然在那里如果要在} 方法在每次翻转之间擦除集合的内容
ArrayList
中存储要翻转的片段,可以使用^{另一个可能的问题是,您正在检查对方玩家,然后立即开始填充
addToPiecesToTurn
。但是,该方向的棋子不一定可以旋转,除非它们被包含当前玩家棋子的第二个位置“夹住”。我认为您的代码没有正确地检查这种情况;当这种情况发生时,您可能希望以某种方式跳过将这些片段翻转给其他播放器,例如清除piecesToTurn
数组编辑:查看当前的解决方案,您将分别实现每个方向,您将有大量重复的代码。如果您考虑沿某个方向行走意味着什么,可以将其视为按“步长”量调整x/y值。步长量可以是向后的
-1
,不移动的0
,或向前的1
。然后,您可以创建一个处理所有方向的方法,而无需复制逻辑:您需要实现
isValid
来检查位置是否有效,即在线路板中。然后可以为每个方向调用此方法:# 3 楼答案
对于某些单元测试来说,这类问题已经成熟。你可以很容易地设立一个董事会,玩一个动作,并验证答案,测试结果将提供大量的洞察你的期望和现实分歧