package Q9; import java.util.*; public class MovingRobot extends Robot { private ArrayList moves = new ArrayList(); private int nextMove; public MovingRobot(int x, int y) { super(x, y); } public boolean validateNextMove() { return validateNextMove(nextMove); } public boolean validateNextMove(int direction) { switch (direction) { case Robot.UP: return canMoveUp(); case Robot.RIGHT_UP_CORNER: return canMoveUp() && canMoveRight(); case Robot.RIGHT: return canMoveRight(); case Robot.RIGHT_DOWN_CORNER: return canMoveDown() && canMoveRight(); case Robot.DOWN: return canMoveDown(); case Robot.LEFT_DOWN_CORNER: return canMoveDown() && canMoveLeft(); case Robot.LEFT: return canMoveLeft(); case Robot.LEFT_UP_CORNER: return canMoveLeft() && canMoveUp(); default: return false; } } public int generateNextMove() { return new Random().nextInt(7) + 1; } public static boolean sameSlot(Robot r1, Robot r2) { return r1.getX() == r2.getX() && r1.getY() == r2.getY(); } public String printMoves() { ArrayList printableMoves = new ArrayList(); for (Integer move : this.moves) printableMoves.add(String.valueOf(move)); return String.join(",", printableMoves); } public void move() { this.nextMove = generateNextMove(); if (!validateNextMove(this.nextMove)) this.move(); this.move(this.nextMove); } public void move(int direction) { if (!validateNextMove(direction)) return; switch (direction) { case Robot.UP: moveUp(); break; case Robot.RIGHT_UP_CORNER: moveUp(); moveRight(); break; case Robot.RIGHT: moveRight(); break; case Robot.RIGHT_DOWN_CORNER: moveDown(); moveRight(); break; case Robot.DOWN: moveDown(); break; case Robot.LEFT_DOWN_CORNER: moveDown(); moveLeft(); break; case Robot.LEFT: moveLeft(); break; case Robot.LEFT_UP_CORNER: moveLeft(); moveUp(); break; default: return; } moves.add(direction); } private boolean canMoveUp() { return this.getY() > 0; } private boolean canMoveDown() { return this.getY() < 9; } private boolean canMoveRight() { return this.getX() < 9; } private boolean canMoveLeft() { return this.getX() > 0; } private void moveUp() { this.setY(this.getY() - 1); } private void moveDown() { this.setY(this.getY() + 1); } private void moveRight() { this.setX(this.getX() + 1); } private void moveLeft() { this.setX(this.getX() - 1); } public static void main(String[] args) { System.out.println("=== Question 9 ==="); MovingRobot r1 = new MovingRobot(0, 0); MovingRobot r2 = new MovingRobot(9, 9); while (!MovingRobot.sameSlot(r1, r2)) { r1.move(); r2.move(); System.out.println( String.format("R1 (%d, %d), R2 (%d, %d)", r1.getX(), r1.getY(), r2.getX(), r2.getY())); } System.out.println(String.format("Collision at: (%d, %d)", r1.getX(), r1.getY())); System.out.println(String.format("R1 Route: [%s]", r1.printMoves())); System.out.println(String.format("R2 Route: [%s]", r2.printMoves())); } }