Grid
unknown
java
3 years ago
2.6 kB
8
Indexable
package com.alt2; import java.util.ArrayList; /* Represents our grid. This would ease further implementation. If we were to add additional robots, or wanted to add other objects to the grid. */ public class Grid { Robot[][] grid = new Robot[5][5]; // Initalize a 5x5 grid that can store robots. Robot robot = new Robot(0, 0, 90); // adding a robot to the southwest of our grid, facing north. public Grid() { } /* Method for itterationg over our list of arguments. Spliting the arguments when necessary. */ public void handleCommand(ArrayList<String> commands) { boolean robotPlaced = false; for (String arg : commands) { if (arg.contains("PLACE")) { String[] arrOfStr = arg.split(" ", 2); String[] values = arrOfStr[1].split(",", 3); if (checkValidPlacement(Integer.parseInt(values[0]), Integer.parseInt(values[1]))) { robot.place(Integer.parseInt(values[0]), Integer.parseInt(values[1]), values[2]); robotPlaced = true; } } if (robotPlaced) { if (arg.equals("MOVE")) updateRobot(); if (arg.equals("LEFT")) robot.rotate(-90); if (arg.equals("RIGHT")) robot.rotate(90); if (arg.equals("REPORT")) System.out.println(robot.print()); } updateGrid(); } } /* Updates the robots postion every time we issue a command. */ public void updateGrid() { try { grid[robot.getPosX()][robot.getPosY()] = robot; } catch (Exception e) { grid[0][0] = robot; } } /* Method the will move our robot, we save our current valid postion before attempting a move. Checking if the placement is valid. */ public void updateRobot() { int tempX = robot.getPosX(); int tempY = robot.getPosY(); robot.move(); if (!checkValidPlacement(robot.getPosX(), robot.getPosY())) { System.out.println("Invalid move"); robot.setPosX(tempX); robot.setPosY(tempY); } } public boolean checkValidPlacement(int x, int y) { if (x > grid.length || x < 0) { return false; } if (y > grid[0].length || y < 0) { return false; } return true; } }
Editor is loading...