// Author: benson limketkai // Date: May 22, 2007 // Modified: June 3, 2008 import java.awt.*; // a robot class -- notice how the robot has no notion of // world coordinates (i.e. the individual pixel coordinates // of the drawing panel); in all computations, it only thinks // in terms of grid coordinates; the World class abstracts // away any details about drawing on the drawing panel public class Robot { private Point location; private Direction heading; private World grid; public Robot(World grid) { heading = Direction.EAST; location = new Point(); this.grid = grid; } ///////////////////////////////////////////////////////// // accessors ///////////////////////////////////////////////////////// public double getX() { return location.x; } public double getY() { return location.y; } ///////////////////////////////////////////////////////// // changes the heading of the robot public void turn(boolean turnRight) { Direction[] dirs = { Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST }; for (int i = 0; i < dirs.length; i++) { if (heading == dirs[i]) { if (turnRight) { heading = dirs[(i+1)%dirs.length]; } else { heading = dirs[(i+3)%dirs.length]; } return; // heading changed, exit } } } // move the robot NUM number of steps in the direction of the heading; // if the robot exceeds the bounds of the world, put them on the edge public void move(int num) { if (heading == Direction.NORTH) { location.translate(0, num); int maxY = grid.getMaxY(); if (getY() > maxY) { location.y = maxY; } } else if (heading == Direction.SOUTH) { location.translate(0, -num); int minY = grid.getMinY(); if (getY() < minY) { location.y = minY; } } else if (heading == Direction.EAST) { location.translate(num, 0); int maxX = grid.getMaxX(); if (getX() > maxX) { location.x = maxX; } } else if (heading == Direction.WEST) { location.translate(-num, 0); int minX = grid.getMinX(); if (getX() < minX) { location.x = minX; } } } // draws the robot in the grid public void draw(World grid) { grid.setColor(Color.RED); // draw body grid.fillCircle(getX(), getY(), 0.5); // draw heading double angle; if (heading == Direction.NORTH) { angle = Math.toRadians(90); } else if (heading == Direction.SOUTH) { angle = Math.toRadians(-90); } else if (heading == Direction.EAST) { angle = 0; } else { // WEST angle = Math.toRadians(180); } // draw arrow double endX = getX() + (1.5 * Math.cos(angle)); double endY = getY() + (1.5 * Math.sin(angle)); grid.drawLine(getX(), getY(), endX, endY, 0.25); // draw endpoint of arrow double arrowEnd1X = endX + (0.75 * Math.cos(angle - Math.toRadians(135))); double arrowEnd1Y = endY + (0.75 * Math.sin(angle - Math.toRadians(135))); grid.drawLine(arrowEnd1X, arrowEnd1Y, endX, endY, 0.25); double arrowEnd2X = endX + (0.75 * Math.cos(angle + Math.toRadians(135))); double arrowEnd2Y = endY + (0.75 * Math.sin(angle + Math.toRadians(135))); grid.drawLine(arrowEnd2X, arrowEnd2Y, endX, endY, 0.25); } }