/* * Mouse in a Maze Program * * Class: RandomMouse * * Author: Alyce Brady * * License: * This program is free software; you can redistribute it * and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ import java.util.ArrayList; import java.util.Random; import edu.kzoo.grid.Grid; import edu.kzoo.grid.Location; import edu.kzoo.util.RandNumGenerator; /** * Mouse in a Maze Program:
* The RandomMouse class defines a mouse that moves randomly in a maze * unless it is next to the cheese, in which case it moves there. * * @author Alyce Brady * @version 4 October 2025 **/ public class RandomMouse extends Mouse { // Inherit everything except the constructor; redefine the nextLocation // method. /** Constructs a RandomMouse object. **/ public RandomMouse() { super(); } /** {@inheritDoc} *

* A random mouse may move to any adjacent location that is empty or * contains cheese, including the one it just came from, although it * will always choose to move to the cheese if that is one of the * possibilities. If this mouse cannot move, * nextLocation returns its current location. *

**/ @Override protected Location nextLocation() { // Figure out which neighbors of the mouse's current location are // empty or contain cheese and so could be possible next locations. ArrayList posNextLocs = maze().possibleNextLocations(location()); // If there are no valid possible next locations, then we're done. if ( posNextLocs.size() == 0 ) return location(); // Does the list of possible next locations include the cheese? If // so, that should be the next location. if ( posNextLocs.contains(maze().getFinishLoc()) ) return maze().getFinishLoc(); // Otherwise, return a randomly chosen neighboring empty location. Random randNumGen = RandNumGenerator.getInstance(); int randNum = randNumGen.nextInt(posNextLocs.size()); return posNextLocs.get(randNum); } }