/** * Tests whether this jumper can move forward into a location. * * @return true if this jumper can move. */ public boolean canMove() { // If the jumper is not in the grid, it cannot move. Grid<Actor> gr = getGrid(); if (gr == null) { return false; } Location loc = getLocation(); // If the location in front of the jumper is out of the grid, it cannot move. Location nextOne = loc.getAdjacentLocation(getDirection()); if (!gr.isValid(nextOne)) { return false; } // If the location two cells in front is out of the grid, it cannot move. Location nextTwo = nextOne.getAdjacentLocation(getDirection()); if (!gr.isValid(nextTwo)) { return false; } Actor neighbor = gr.get(nextTwo); return (neighbor == null) || (neighbor instanceof Flower) || (neighbor instanceof Rock); // ok to move into empty location or onto flower and rock. // not ok to move onto any other actor }
/** Moves the jumper forward */ public void move() { Grid<Actor> gr = getGrid(); if (gr == null) return; Location loc = getLocation(); Location next = loc.getAdjacentLocation(getDirection()); if (gr.isValid(next)) moveTo(next); else removeSelfFromGrid(); }
private String getToolTipText(Location loc) { if (!toolTipsEnabled || loc == null || !grid.isValid(loc)) return null; Object f = grid.get(loc); if (f != null) return MessageFormat.format( resources.getString("cell.tooltip.nonempty"), new Object[] {loc, f}); else return MessageFormat.format(resources.getString("cell.tooltip.empty"), new Object[] {loc, f}); }
public boolean canMove() { Grid<Actor> gr = getGrid(); if (gr == null) return false; Location loc = getLocation(); Location next = loc.getAdjacentLocation(getDirection()).getAdjacentLocation(getDirection()); if (!gr.isValid(next)) return false; Actor neighbor = gr.get(next); return (neighbor == null) || (neighbor instanceof Flower); }
/** * Draws the occupants of the grid. * * @param g2 the graphics context */ private void drawOccupants(Graphics2D g2) { ArrayList<Location> occupantLocs = grid.getOccupiedLocations(); for (int index = 0; index < occupantLocs.size(); index++) { Location loc = (Location) occupantLocs.get(index); int xleft = colToXCoord(loc.getCol()); int ytop = rowToYCoord(loc.getRow()); drawOccupant(g2, xleft, ytop, grid.get(loc)); } }
/** * Finds the valid adjacent locations of giving position critter in different directions. * * @param directions - an array of directions (which are relative to the current direction) * @param loc - A position inside the grid. * @return a set of valid locations that are neighbors of the current location in the given * directions */ public ArrayList<Location> getLocationsInDirections(int[] directions, Location loc) { ArrayList<Location> locs = new ArrayList<Location>(); Grid gr = getGrid(); for (int d : directions) { Location neighborLoc = loc.getAdjacentLocation(getDirection() + d); if (gr.isValid(neighborLoc)) locs.add(neighborLoc); } return locs; }
public void step() { Grid<Actor> gr = getGrid(); ArrayList<Actor> actors = new ArrayList<Actor>(); for (Location loc : gr.getOccupiedLocations()) actors.add(gr.get(loc)); for (Actor a : actors) { // only act if another actor hasn't removed a if (a.getGrid() == gr) a.act(); } }
/** * Tests whether this jumper can move forward into a location that is empty * * @return true if this jumper can move. */ public boolean canMove() { Grid<Actor> gr = getGrid(); if (gr == null) return false; Location loc = getLocation(); Location next = loc.getAdjacentLocation(getDirection()); if (!gr.isValid(next)) return false; Actor neighbor = gr.get(next); return (neighbor == null); // ok to move into empty location // not ok to move onto any other actor }
public void move() { Grid<Actor> gr = getGrid(); if (gr == null) return; Location loc = getLocation(); Location next = loc.getAdjacentLocation(getDirection()); if (gr.isValid(next)) { nextActor = gr.get(next); moveTo(next); if (oldActor != null) oldActor.putSelfInGrid(gr, loc); oldActor = nextActor; } else removeSelfFromGrid(); }
/** * Sets a new grid for this world. Occupants are transferred from the old world to the new. * * @param newGrid the new grid */ public void setGrid(Grid<T> newGrid) { Grid<T> oldGrid = world.getGrid(); Map<Location, T> occupants = new HashMap<Location, T>(); for (Location loc : oldGrid.getOccupiedLocations()) occupants.put(loc, world.remove(loc)); world.setGrid(newGrid); for (Location loc : occupants.keySet()) { if (newGrid.isValid(loc)) world.add(loc, occupants.get(loc)); } display.setGrid(newGrid); repaint(); }
public boolean canMove(Location nextLocation) { Grid<Actor> gr = getGrid(); if (gr == null) { return false; } if (!gr.isValid(nextLocation)) { return false; } Actor neighbor = gr.get(nextLocation); return (neighbor == null) || (neighbor instanceof Flower); }
/** * Generates the next generation based on the rules of the Game of Life and updates the grid * associated with the world * * @pre the game has been initialized * @post the world has been populated with a new grid containing the next generation */ public void createNextGeneration() { /** * You will need to read the documentation for the World, Grid, and Location classes in order to * implement the Game of Life algorithm and leverage the GridWorld framework. */ // create the grid, of the specified size, that contains Actors Grid<Actor> grid = world.getGrid(); // insert magic here... BoundedGrid<Actor> newgrid = new BoundedGrid<Actor>(ROWS, COLS); int col = getNumCols(); int row = getNumRows(); for (int column = 0; column < col; column++) { for (int rows = 0; rows < row; rows++) { Actor cell = getActor(rows, column); Location location = new Location(rows, column); if (cell != null) { ArrayList<Actor> Neighbors = grid.getNeighbors(location); int Neighborscount = Neighbors.size(); if (Neighborscount == 3) { // lives Rock newrock1 = new Rock(); Location newloc1 = new Location(rows, column); newgrid.put(newloc1, newrock1); } else if (Neighborscount == 2) { // lives Rock newrock1 = new Rock(); Location newloc1 = new Location(rows, column); newgrid.put(newloc1, newrock1); } else if (Neighborscount < 3) { // dies } else if (Neighborscount > 3) { // dies } } else if (cell == null) { ArrayList<Actor> Neighbors = grid.getNeighbors(location); int Neighborscount = Neighbors.size(); if (Neighborscount == 3) { // reborn Rock newrock1 = new Rock(); Location newloc1 = new Location(rows, column); newgrid.put(newloc1, newrock1); } } } } world.setGrid(newgrid); world.show(); }
/** Moves the jumper forward two cells. */ public void move() { Grid<Actor> gr = getGrid(); if (gr == null) { return; } Location loc = getLocation(); Location next = loc.getAdjacentLocation(getDirection()); Location nextTwo = next.getAdjacentLocation(getDirection()); if (gr.isValid(nextTwo)) { moveTo(nextTwo); } else { removeSelfFromGrid(); } }
public boolean canMove() { Grid<Actor> gr = getGrid(); if (gr == null) return false; Location loc = getLocation(); Location next = loc.getAdjacentLocation(getDirection()); if (!gr.isValid(next)) return false; Actor neighbor = gr.get(next); return (neighbor == null) || (neighbor instanceof TallGrass) || (neighbor instanceof Green) || (neighbor instanceof Path) || (neighbor instanceof Cave43) || (neighbor instanceof Cave33); // not ok to move onto water or rocks }
/** * Creates the actors and inserts them into their initial starting positions in the grid * * @pre the grid has been created * @post all actors that comprise the initial state of the game have been added to the grid */ private void populateGame(boolean test) { // constants for the location of the three cells initially alive // the grid of Actors that maintains the state of the game // (alive cells contains actors; dead cells do not) Grid<Actor> grid = world.getGrid(); Random rand = new Random(); int n; // Nunmber variable for random number // Runs for regular program if (test == false) { // Randomly places an actor at coordinates (a, i) for (int i = 0; i <= 1000; i++) { for (int a = 0; a <= 1000; a++) { n = rand.nextInt(10); // Randomly chooses where an actor is initially placed on a grid if (n == 2 || n == 5 || n == 7 || n == 9 || n == 1) { Actor rock1 = new Actor(); Location loc1 = new Location(i, a); grid.put(loc1, rock1); } } } } // Tested version (Works if this is placed as code for populateGame) if (test == true) { for (int i = 0; i <= 4; i++) { for (int a = 0; a <= 4; a++) { if (i == 0 && a == 0 || i == 0 && a == 4 || i == 1 && a == 1 || i == 1 && a == 3 || i == 2 && a == 2 || i == 3 && a == 1 || i == 3 && a == 3 || i == 4 && a == 0 || i == 4 && a == 4) { Actor rock1 = new Actor(); Location loc1 = new Location(i, a); grid.put(loc1, rock1); } } } } }
/** * Draw the gridlines for the grid. We only draw the portion of the lines that intersect the * current clipping bounds. * * @param g2 the Graphics2 object to use to render */ private void drawGridlines(Graphics2D g2) { Rectangle curClip = g2.getClip().getBounds(); int top = getInsets().top, left = getInsets().left; int miny = Math.max(0, (curClip.y - top) / (cellSize + 1)) * (cellSize + 1) + top; int minx = Math.max(0, (curClip.x - left) / (cellSize + 1)) * (cellSize + 1) + left; int maxy = Math.min(numRows, (curClip.y + curClip.height - top + cellSize) / (cellSize + 1)) * (cellSize + 1) + top; int maxx = Math.min(numCols, (curClip.x + curClip.width - left + cellSize) / (cellSize + 1)) * (cellSize + 1) + left; g2.setColor(Color.GRAY); for (int y = miny; y <= maxy; y += cellSize + 1) for (int x = minx; x <= maxx; x += cellSize + 1) { Location loc = locationForPoint(new Point(x + cellSize / 2, y + cellSize / 2)); if (loc != null && !grid.isValid(loc)) g2.fillRect(x + 1, y + 1, cellSize, cellSize); } g2.setColor(Color.BLACK); for (int y = miny; y <= maxy; y += cellSize + 1) // draw horizontal lines g2.drawLine(minx, y, maxx, y); for (int x = minx; x <= maxx; x += cellSize + 1) // draw vertical lines g2.drawLine(x, miny, x, maxy); }
/** * CREATE A NEW METHOD GETLOCAITONSINDIRECTIONNEW NEED A LOCTION PARAMETER RETURN FURTHER LOCITON * SET FORM THIS LOCATION */ public ArrayList<Location> getLocationsInDirectionsNew(Location locParameter) { ArrayList<Location> locs = new ArrayList<Location>(); Grid gr = getGrid(); Location loc = new Location(locParameter.getRow(), locParameter.getCol()); // PROTECT DATA int[] directions = {Location.LEFT, Location.RIGHT}; for (int d : directions) { Location neighborLoc = loc.getAdjacentLocation(getDirection() + d); if (gr.isValid(neighborLoc) && gr.get(neighborLoc) == null) { // JUDGE LOCATION IS VALID IN THE GRID // JUDGE LOCAITON IS NULL THAT CAN WALK IN locs.add(neighborLoc); } } return locs; }
/** * Sets the grid being displayed. Reset the cellSize to be the largest that fits the entire grid * in the current visible area (use default if grid is too large). * * @param gr the grid to display */ public void setGrid(Grid<?> gr) { currentLocation = new Location(0, 0); JViewport vp = getEnclosingViewport(); // before changing, reset // scroll/pan position if (vp != null) vp.setViewPosition(new Point(0, 0)); grid = gr; originRow = originCol = 0; if (grid.getNumRows() == -1 && grid.getNumCols() == -1) { numRows = numCols = 2000; // This determines the "virtual" size of the pan world } else { numRows = grid.getNumRows(); numCols = grid.getNumCols(); } recalculateCellSize(MIN_CELL_SIZE); }
public void act() { Grid<Actor> gr = getGrid(); Location location = new Location(6, 0); Location rightLoc = new Location(6, 19); if (oldActor instanceof Cave33) { if (getLocation().equals(new Location(3, 15))) { removeSelfFromGrid(); oldActor.putSelfInGrid(gr, new Location(3, 15)); oldActor = gr.get(new Location(11, 10)); putSelfInGrid(gr, new Location(11, 10)); directionSuffix = "down"; } else { if (getLocation().equals(new Location(10, 10))) { removeSelfFromGrid(); oldActor.putSelfInGrid(gr, new Location(10, 10)); oldActor = gr.get(new Location(4, 15)); putSelfInGrid(gr, new Location(4, 15)); directionSuffix = "down"; } } } if (getLocation().equals(location)) { if ((world2 == true) && (switched == false)) { ((PokemonGrid) gr).fillWorld1(); oldActor = gr.get(new Location(6, 19)); putSelfInGrid(gr, new Location(6, 19)); world2 = false; switched = true; } } else { if (getLocation().equals(rightLoc)) { if ((world2 == false) && (switched == false)) { ((PokemonGrid) gr).fillWorld2(); oldActor = gr.get(new Location(6, 0)); putSelfInGrid(gr, new Location(6, 0)); world2 = true; switched = true; } } else switched = false; } }
public void move() { Grid<Actor> gr = getGrid(); if (gr == null) { return; } if (getLocation().equals(targetLocation)) { Location oldTargetLocation = targetLocation; targetLocation = initialLocation; initialLocation = oldTargetLocation; return; } Location loc = getLocation(); Location nextLocation = calculateNextLocation(loc); if (canMove(nextLocation)) { setDirection(loc.getDirectionToward(nextLocation)); moveTo(nextLocation); } else { ArrayList<Location> availableLocations = gr.getEmptyAdjacentLocations(getLocation()); if (availableLocations.get(0) != null) // if not empty { int totalDifference = 0; int leastDifference = 10; Location leastDifferenceLocation = availableLocations.get(0); for (int i = 0; i < availableLocations.size(); i++) { totalDifference += Math.abs(availableLocations.get(i).getCol() - targetLocation.getCol()); totalDifference += Math.abs(availableLocations.get(i).getRow() - targetLocation.getRow()); if (totalDifference < leastDifference) { leastDifference = totalDifference; leastDifferenceLocation = availableLocations.get(i); } totalDifference = 0; } setDirection(loc.getDirectionToward(leastDifferenceLocation)); moveTo(leastDifferenceLocation); } } }
/** @return list of empty locations that are two spaces to its right or left. */ public ArrayList<Location> getMoveLocations() { ArrayList<Location> locs = new ArrayList<Location>(); Grid gr = getGrid(); Location loc1 = getLocation().getAdjacentLocation(getDirection() + Location.LEFT); if (gr.isValid(loc1) && gr.get(loc1) == null) { int[] dirs1 = {Location.LEFT}; for (Location loc : getLocationsInDirections(dirs1, loc1)) if (getGrid().get(loc) == null) locs.add(loc); } Location loc2 = getLocation().getAdjacentLocation(getDirection() + Location.RIGHT); if (gr.isValid(loc2) && gr.get(loc2) == null) { int[] dirs2 = {Location.RIGHT}; for (Location loc : getLocationsInDirections(dirs2, loc2)) if (getGrid().get(loc) == null) locs.add(loc); } if (locs.size() == 0) { return super.getMoveLocations(); } else { return locs; } }
/** * Moves the current location by a given amount. * * @param dr the number of rows by which to move the location * @param dc the number of columns by which to move the location */ public void moveLocation(int dr, int dc) { Location newLocation = new Location(currentLocation.getRow() + dr, currentLocation.getCol() + dc); if (!grid.isValid(newLocation)) return; currentLocation = newLocation; JViewport viewPort = getEnclosingViewport(); if (isPannableUnbounded()) { if (originRow > currentLocation.getRow()) originRow = currentLocation.getRow(); if (originCol > currentLocation.getCol()) originCol = currentLocation.getCol(); Dimension dim = viewPort.getSize(); int rows = dim.height / (cellSize + 1); int cols = dim.width / (cellSize + 1); if (originRow + rows - 1 < currentLocation.getRow()) originRow = currentLocation.getRow() - rows + 1; if (originCol + rows - 1 < currentLocation.getCol()) originCol = currentLocation.getCol() - cols + 1; } else if (viewPort != null) { int dx = 0; int dy = 0; Point p = pointForLocation(currentLocation); Rectangle locRect = new Rectangle(p.x - cellSize / 2, p.y - cellSize / 2, cellSize + 1, cellSize + 1); Rectangle viewRect = viewPort.getViewRect(); if (!viewRect.contains(locRect)) { while (locRect.x < viewRect.x + dx) dx -= cellSize + 1; while (locRect.y < viewRect.y + dy) dy -= cellSize + 1; while (locRect.getMaxX() > viewRect.getMaxX() + dx) dx += cellSize + 1; while (locRect.getMaxY() > viewRect.getMaxY() + dy) dy += cellSize + 1; Point pt = viewPort.getViewPosition(); pt.x += dx; pt.y += dy; viewPort.setViewPosition(pt); } } repaint(); showTip(getToolTipText(currentLocation), pointForLocation(currentLocation)); }
/** * Creates the actors and inserts them into their initial starting positions in the grid * * @pre the grid has been created * @post all actors that comprise the initial state of the game have been added to the grid */ private void populateGame() { // constants for the location of the three cells initially alive final int X1 = 0, Y1 = 4; final int X2 = 1, Y2 = 3; final int X3 = 1, Y3 = 5; final int X4 = 2, Y4 = 2; final int X5 = 2, Y5 = 6; final int X6 = 3, Y6 = 1; final int X7 = 3, Y7 = 3; final int X8 = 3, Y8 = 5; final int X9 = 3, Y9 = 7; final int X10 = 4, Y10 = 0; final int X11 = 4, Y11 = 4; final int X12 = 4, Y12 = 8; final int X13 = 5, Y13 = 1; final int X14 = 5, Y14 = 3; final int X15 = 5, Y15 = 5; final int X16 = 5, Y16 = 7; final int X17 = 6, Y17 = 2; final int X18 = 6, Y18 = 6; final int X19 = 7, Y19 = 3; final int X20 = 7, Y20 = 5; final int X21 = 8, Y21 = 4; // the grid of Actors that maintains the state of the game // (alive cells contains actors; dead cells do not) Grid<Actor> grid = world.getGrid(); // create and add rocks (a type of Actor) to the three intial locations Rock rock1 = new Rock(); Location loc1 = new Location(Y1, X1); grid.put(loc1, rock1); Rock rock2 = new Rock(); Location loc2 = new Location(Y2, X2); grid.put(loc2, rock2); Rock rock3 = new Rock(); Location loc3 = new Location(Y3, X3); grid.put(loc3, rock3); Rock rock4 = new Rock(); Location loc4 = new Location(Y4, X4); grid.put(loc4, rock4); Rock rock5 = new Rock(); Location loc5 = new Location(Y5, X5); grid.put(loc5, rock5); Rock rock6 = new Rock(); Location loc6 = new Location(Y6, X6); grid.put(loc6, rock6); Rock rock7 = new Rock(); Location loc7 = new Location(Y7, X7); grid.put(loc7, rock7); Rock rock8 = new Rock(); Location loc8 = new Location(Y8, X8); grid.put(loc8, rock8); Rock rock9 = new Rock(); Location loc9 = new Location(Y9, X9); grid.put(loc9, rock9); Rock rock10 = new Rock(); Location loc10 = new Location(Y10, X10); grid.put(loc10, rock10); Rock rock11 = new Rock(); Location loc11 = new Location(Y11, X11); grid.put(loc11, rock11); Rock rock12 = new Rock(); Location loc12 = new Location(Y12, X12); grid.put(loc12, rock12); Rock rock13 = new Rock(); Location loc13 = new Location(Y13, X13); grid.put(loc13, rock13); Rock rock14 = new Rock(); Location loc14 = new Location(Y14, X14); grid.put(loc14, rock14); Rock rock15 = new Rock(); Location loc15 = new Location(Y15, X15); grid.put(loc15, rock15); Rock rock16 = new Rock(); Location loc16 = new Location(Y16, X16); grid.put(loc16, rock16); Rock rock17 = new Rock(); Location loc17 = new Location(Y17, X17); grid.put(loc17, rock17); Rock rock18 = new Rock(); Location loc18 = new Location(Y18, X18); grid.put(loc18, rock18); Rock rock19 = new Rock(); Location loc19 = new Location(Y19, X19); grid.put(loc19, rock19); Rock rock20 = new Rock(); Location loc20 = new Location(Y20, X20); grid.put(loc20, rock20); Rock rock21 = new Rock(); Location loc21 = new Location(Y21, X21); grid.put(loc21, rock21); }
/** * Constructs a WorldFrame that displays the occupants of a world * * @param world the world to display */ public WorldFrame(World<T> world) { this.world = world; count++; resources = ResourceBundle.getBundle(getClass().getName() + "Resources"); try { System.setProperty("sun.awt.exception.handler", GUIExceptionHandler.class.getName()); } catch (SecurityException ex) { // will fail in an applet } addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent event) { count--; if (count == 0) System.exit(0); } }); displayMap = new DisplayMap(); String title = System.getProperty("info.gridworld.gui.frametitle"); if (title == null) title = resources.getString("frame.title"); setTitle(title); setLocation(25, 15); URL appIconUrl = getClass().getResource("GridWorld.gif"); ImageIcon appIcon = new ImageIcon(appIconUrl); setIconImage(appIcon.getImage()); makeMenus(); JPanel content = new JPanel(); content.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15)); content.setLayout(new BorderLayout()); setContentPane(content); display = new GridPanel(displayMap, resources); KeyboardFocusManager.getCurrentKeyboardFocusManager() .addKeyEventDispatcher( new KeyEventDispatcher() { public boolean dispatchKeyEvent(KeyEvent event) { if (getFocusOwner() == null) return false; String text = KeyStroke.getKeyStrokeForEvent(event).toString(); final String PRESSED = "pressed "; int n = text.indexOf(PRESSED); if (n < 0) return false; // filter out modifier keys; they are neither characters or actions if (event.getKeyChar() == KeyEvent.CHAR_UNDEFINED && !event.isActionKey()) return false; text = text.substring(0, n) + text.substring(n + PRESSED.length()); boolean consumed = getWorld().keyPressed(text, display.getCurrentLocation()); if (consumed) repaint(); return consumed; } }); JScrollPane scrollPane = new JScrollPane(); scrollPane.setViewport(new PseudoInfiniteViewport(scrollPane)); scrollPane.setViewportView(display); content.add(scrollPane, BorderLayout.CENTER); gridClasses = new TreeSet<Class>( new Comparator<Class>() { public int compare(Class a, Class b) { return a.getName().compareTo(b.getName()); } }); for (String name : world.getGridClasses()) try { gridClasses.add(Class.forName(name)); } catch (Exception ex) { ex.printStackTrace(); } Grid<T> gr = world.getGrid(); gridClasses.add(gr.getClass()); makeNewGridMenu(); control = new GUIController<T>(this, display, displayMap, resources); content.add(control.controlPanel(), BorderLayout.SOUTH); messageArea = new JTextArea(2, 35); messageArea.setEditable(false); messageArea.setFocusable(false); messageArea.setBackground(new Color(0xFAFAD2)); content.add(new JScrollPane(messageArea), BorderLayout.NORTH); pack(); repaint(); // to show message display.setGrid(gr); }
public boolean isPannableUnbounded() { return grid != null && (grid.getNumRows() == -1 || grid.getNumCols() == -1); }
public void getOldActor(Grid gr, Location loc) { oldActor = (Actor) (gr.get(new Location(6, 10))); }