1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- import java.util.LinkedList;
- import java.util.Queue;
-
- public class SnakeBot extends Bot {
- protected final static String obstacles = "~#X*";
- protected boolean offByOne = true;
- protected int currentStepCount = 0;
- protected int steps = 0;
-
- public static void main(String[] args) {
- while (true) {
- Bot bot = new SnakeBot(args);
- bot.run();
- }
- }
-
- protected SnakeBot(String[] args) {
- super(args);
- }
-
- @Override
- protected char nextMove(View view) throws Exception {
- System.out.println();
- String data = view.data;
- char[][] grid = dataToGrid(view.data, view.width);
-
- if (data.contains("@")) {
- return breadthFirstSearch(grid);
- } else {
- return walkAround(grid);
- }
- }
-
- protected char[][] dataToGrid(String data, int width) {
- int height = data.length() / width;
- char[][] grid = new char[width][height];
- for (int i = 0; i < data.length(); i++) {
- grid[i % width][i / width] = data.charAt(i);
- }
- return grid;
- }
-
- protected char walkAround(char[][] grid) {
- if (steps == 0) {
- currentStepCount++;
- if (offByOne) {
- currentStepCount++;
- }
- offByOne = !offByOne;
- steps = currentStepCount;
- return '>';
- } else {
- steps--;
- return safeMove(grid);
- }
- }
-
- protected char safeMove(char[][] grid) {
- int size = grid.length;
- if (grid[size / 2][size / 2 - 1] == '*') {
- return '<';
- } else {
- return '^';
- }
- }
-
- protected char breadthFirstSearch(char[][] grid) {
- int width = grid[0].length;
- int height = grid.length;
- int startX = width / 2;
- int startY = height / 2;
-
- Queue<Move> queue = new LinkedList<>();
- queue.add(new Move(startX, startY - 1, '^'));
- queue.add(new Move(startX, startY + 1, '>'));
- queue.add(new Move(startX + 1, startY, '>'));
- queue.add(new Move(startX - 1, startY, '<'));
-
- while (!queue.isEmpty()) {
- Move move = queue.poll();
- if (move.x < 0 || move.x >= width || move.y < 0 || move.y >= height) continue;
- if (obstacles.contains("" + grid[move.x][move.y])) continue;
- if (grid[move.x][move.y] == '@') return move.direction;
-
- queue.add(new Move(move.x, move.y - 1, move.direction));
- queue.add(new Move(move.x, move.y + 1, move.direction));
- queue.add(new Move(move.x + 1, move.y, move.direction));
- queue.add(new Move(move.x - 1, move.y, move.direction));
- }
-
- System.err.println("No path found");
- return safeMove(grid);
- }
-
- protected record Move(int x, int y, char direction) {
- }
-
- }
|