Added countUncollectedStones for avoiding endless loops.

This commit is contained in:
Illia Soloviov 2024-01-07 19:38:17 +01:00
parent c88707fee9
commit 2d6def3c29

View File

@ -13,7 +13,7 @@
public class SnakeBot extends Bot{ public class SnakeBot extends Bot{
String moves = ""; String moves = "";
private int spiralNumber = 0; private int spiralNumber = 0;
private boolean ignoreStone = false; private boolean ignoreStones = false;
public static void main(String[] args) { public static void main(String[] args) {
Bot snakeBot = new SnakeBot(args); Bot snakeBot = new SnakeBot(args);
snakeBot.run(); snakeBot.run();
@ -26,19 +26,35 @@ public class SnakeBot extends Bot{
protected char nextMove(View view) { protected char nextMove(View view) {
boolean stoneDetected = view.data.contains("@"); boolean stoneDetected = view.data.contains("@");
char nextMove; char nextMove;
nextMove = (stoneDetected && !ignoreStone) ? goToStone(view) : walkBySpiral(view); nextMove = (stoneDetected && !ignoreStones) ? goToStone(view) : walkBySpiral(view);
int centerCoordinateOfView = view.width / 2; int centerCoordinateOfView = view.width / 2;
int frontCellIndex = calculateCharIndexFromCoordinates(view.width, centerCoordinateOfView, centerCoordinateOfView - 1); int frontCellIndex = calculateCharIndexFromCoordinates(view.width, centerCoordinateOfView, centerCoordinateOfView - 1);
if(nextMove == '^' && view.data.charAt(frontCellIndex) == '*'){ if(nextMove == '^' && view.data.charAt(frontCellIndex) == '*'){
nextMove = (countCollectedStonesLeft(view) <= countCollectedStonesRight(view)) ? '<' : '>'; nextMove = (countCollectedStonesLeft(view) <= countCollectedStonesRight(view)) ? '<' : '>';
ignoreStone = true; ignoreStones = true;
} }
if(countCollectedStones(view) <= 2) ignoreStone = false; /*
* @TODO:
* Avoiding endless loops due to trying to collect two stones at once.
* Problem: stones located near to each other are ignored.
*/
if(countUncollectedStones(view) > 1) ignoreStones = true;
if(countCollectedStones(view) <= 2 && countUncollectedStones(view) <= 1) ignoreStones = false;
return nextMove; return nextMove;
} }
private int countUncollectedStones(View view) {
int count = 0;
for (char c : view.data.toCharArray()) {
if (c == '@') count++;
}
return count;
}
private int countCollectedStonesLeft(View view) { private int countCollectedStonesLeft(View view) {
int[] leftSide = generateLeftSideArray(view.width); int[] leftSide = generateLeftSideArray(view.width);
int stones = 0; int stones = 0;
@ -61,9 +77,7 @@ public class SnakeBot extends Bot{
int count = 0; int count = 0;
for (char c : view.data.toCharArray()) { for (char c : view.data.toCharArray()) {
if (c == '*') { if (c == '*') count++;
count++;
}
} }
return count; return count;
} }