Question
Create a MineWalker game that lets a user start from the lower-left corner on a grid and attempt to walk to the upper-right corner while
Create a MineWalker game that lets a user start from the lower-left corner on a grid and attempt to walk to the upper-right corner while avoiding hidden mines.
Classes that you will create MineWalker.java (driver) MineWalkerPanel.java (extends JPanel) MineFieldPanel.java (extends JPanel) MineFieldButton.java (extends JButton)
Existing class and interface that you will use RandomWalk.java (code copied below) RandomWalkInterface.java (code copied below)
Objectives Write a program with a Graphical User Interface (GUI) Design a good user interface Use classes from the AWT and Swing packages Use existing classes Use events and listeners
Specification User interface design. Design a layout for the user interface. This is best done on a white board or on paper! ? The main visual element will be the grid of tiles that represents the mine field. This can be a two-dimensional array of JButton objects. ? You will also need buttons for starting a new game, a text field for the grid size, buttons for showing/hiding the mines and labels for the current score and number of lives as well as other optional elements. ? Plan on changing labels on buttons and disabling them when it doesn't make sense to use them. For example, the grid size cannot be changed while the game is going on. Once the user clicks on the Show Mines button, its label should change to Hide Mines. Once the game starts, the label for the New Game button should change to Give Up. Note that the labels can be different if that makes more sense to you.
Creating the game. The New Game button creates a new game as follows. ? Generate a new grid of the size specified by the user (have reasonable limits on the size). The default size is 10x10. ? Generate a random walk on this grid from the lower-left corner to the upper-right corner. This path will be used to ensure that there is a solution to the game. ? Generate the hidden mines on the grid. Use a random number generator to place mines. 25% of the tiles that are not in the random walk should be mines. You may allow the user to change from the 25% default value but that is extra credit and not required. Game play. ?At each step, the user can move one step to the north, south, west or east of the current position (except around the edges). If a user clicks on a tile that isn't valid, the program doesn't let them move there (no jumping allowed!). The game hints at the number of mines near by with a color code defined as follows:
?Green: There are zero mines in the four adjacent tiles ?Yellow: There is one mine in the four adjacent tiles ?Orange: There are two mines in the four adjacent tiles ?Red: There are three mines in the four adjacent tiles
?If the user reaches the goal, the game is over. Notify the user appropriately using a JOptionPane popup window . When the game is over, show all the mines on the grid along with the path that the user took. Do not allow the user to play anymore unless they start a new game.
? Show current square by a blinking tile color or label. For this you need to create a timer thread for the animation (in the GridMap class). Use the following code for the startAnimation() method and call it from the constructor in MineWalkerPanel class. The animation method creates a Timer that will periodically fire an ActionEvent that needs to be handled by an ActionListener. You need to toggle the color of the button (or its label) in the actionPerformed method. Here is a template for the startAnimation method and the corresponding ActionListener: /** * Performs action when timer event fires. */ private class TimerActionListener implements ActionListener { public void actionPerformed(ActionEvent evt) { // toggle color/text for current tile // do other periodic checks if needed } }
/** * Create an animation thread that runs periodically */ private void startAnimation() { TimerActionListener taskPerformer = new TimerActionListener(); new Timer(DELAY, taskPerformer).start(); }
?If the user steps on a mine, they die and lose one life. The game is over after number of lives reaches zero. The user gets five lives in total. After each death, the user is reborn on the last tile they were on before stepping on a mine. They can continue walking from that spot. Stepping on an already exploded mine should not result in an additional death, but it is not a valid move. Stay out of the craters.
?The score and the number of lives are updated after every move in a label somewhere on the display.
Scoring. Come up with a scoring scheme. For example, the initial score can be 500. Each life costs the user a 100 points. Each step costs them 1 point. The goal is to lose as few points as possible. Or invent your own scoring scheme!
Show/hide mines: Add a button that allows the user to show or hide the mines. This is very useful for debugging!
Show/hide walk: Add a button that allows the user to show or hide the original random walk used to create the game.
Color key: Add a useful key so the user knows what the colors mean in the game.
Settable level of difficulty: Provide a sliding bar that allows the user to set the level of difficulty for the game.
Sound effects: Set sound effects for walking, invalid moves, reaching the goal and, of course, for explosions!
Getting Started
Create a new Eclipse project for this assignment. Import your RandomWalk.java and RandomWalkInterface.java into your project.
Create new classes: ?MineWalker.java - The driver class. Creates the JFrame and add the MineWalkerPanel to the frame. ?MineWalkerPanel.java - The main game panel class. Must extend JPanel. Creates and adds sub-panels. Manages all game components and the ActionListeners. ?MineFieldPanel.java - The mine field panel class. Must extend JPanel. Creates and manages grid of MineFieldButtons. ?MineFieldButton.java - The mine field button class. Must extend JButton. Represents and manages the state of a single button in the MineFieldGrid.
Make a rough sketch of your GUI. Remember the provided screenshots and movies are general guidelines and you should not turn in an exact duplicate of what you see. Be creative. Have fun. Determine the Java classes for the components in your design and label your sketch. Group your sketch into sections (breaking down the design) that will be implemented in the same Java container. Make notes on your diagram about the Layout Manager and Border style you will use for each container. Implement the Java code to produce the GUI you sketched above. Working on one section at a time helps to reduce the overall complexity as you can validate smaller sections of code before putting everything together. Since you will have a large number of components in your GUI, choose variables names that will help you to quickly identify which visual element you are currently dealing with in the code. Once you have the visual framework in place consider the listeners and how they will interact with each component in your design. Decide if you want a single event listener with a compound conditional or if you want separate listeners to handle each event. Implement the game logic and integrate the controls and scoring into the code. Plan early on how you will test and debug each section of the game and ensure you are testing regularly. Ensure you have the basic functionality implemented before improving or adding to the game.
//RandomWalkInterface.java - No changes necessary
import java.awt.Point; import java.util.ArrayList;
/** * Interface to define the methods needed for a RandomWalk class. * */ public interface RandomWalkInterface { /** * Takes a single step towards the destination and adds the new Point to the path. * Steps North or East with equal probability. * * If the step is the final step, sets the value of the done to true. */ public void step();
/** * Takes a single step towards the destination and adds the new Point to the path. * Steps North or East with 90% probability and South or West with 10% probability. * * If the step is the final step, sets the value of the done to true. * * EXTRA CREDIT! Only implement this method if you are attempting the extra credit. */ public void stepEC();
/** * Creates the entire walk in one call by internally using the step() method. */ public void createWalk();
/** * Creates the entire walk in one call by internally using the stepEC() method. * * EXTRA CREDIT! Only implement this method if you are attempting the extra credit. */ public void createWalkEC();
/** * Returns the current value of the done variable. * @return true if the path has reached the destination, false otherwise. */ public boolean isDone();
/** * Returns the grid size of this walk. * @return The size of the grid. */ public int getGridSize();
/** * Returns the starting point of this walk. * @return the starting point. */ public Point getStartPoint();
/** * Returns the ending point of this walk. * @return the ending point. */ public Point getEndPoint();
/** * Returns the current point of this walk. * @return the current point. */ public Point getCurrentPoint();
/** * Returns the path this walk has taken. * @return a copy of the path. */ public ArrayList
}
//RandomWalk.java - help needed in step() and stepEC() methods
import java.awt.Point; import java.util.ArrayList; import java.util.Random;
/** * * */ public class RandomWalk implements RandomWalkInterface {
/** * Instance Data */ private int gridSize = 10; private int step = 0; private boolean isDone = false; private ArrayList
/** * Constructor */ public RandomWalk(int gridSize) { path.add(start); r = new Random(); }
/** * Method Overloading Constructor */ public RandomWalk(int gridSize, long seed) { path.add(start); r = new Random(seed); }
/** * Moves one more step using methods from point class based on parameters * * makes invalid steps, resulting in infinite loop. Also does not set done * Help? */ public void step() { step = r.nextInt(2); Point temp = current; //stepping if (step == 0) { temp = new Point(current.x, current.y); } if (step == 1) { temp = new Point(current.x + 1, current.y); } //checking bounds and adding to array if (temp.x != end.x && temp.y != end.y) { current = temp; path.add(current); } /* checking if done */ if (current.x == end.x || current.y == end.y) { isDone = true; } else { isDone = false; } }
/** * Steps North (0,-) or East (+,0) with 90% probability and South (0,+) or West * (-,0) with 10% probability * * Help? */ public void stepEC() {
}
/** * Generates full walk */ public void createWalk() { while (isDone == false) { step(); } }
/** * Generates full EC walk */ public void createWalkEC() { while (isDone == false) { stepEC(); }
}
/** * returns completion status */ public boolean isDone() { return isDone; }
/** * sets completion status */ public void setDone(boolean b) { this.isDone = isDone; }
/** * Returns grid size */ public int getGridSize() { return gridSize; }
/** * Returns start point */ public Point getStartPoint() { return start; }
/** * Returns end Point */ public Point getEndPoint() { return end; }
/** * returns current point */ public Point getCurrentPoint() { return current; }
/** * returns path */ public ArrayList
/** * returns string list of points */ public String toString() { String pathOfTravel = ""; for (Point point : path) { pathOfTravel = pathOfTravel + "[" + (int) point.getX() + "," + (int) point.getY() + "]";
} return pathOfTravel; }
}
?//MineWalker.java
import javax.swing.JFrame;
/** * * */ public class MineWalker {
/** * Creates a JFrame and adds the main JPanel to the JFrame. * * @param args */ public static void main(String[] args) { JFrame frame = new JFrame("Mine Walker"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new MineWalkerPanel(20, 20)); frame.pack(); frame.setVisible(true);
}
}
?//MineWalkerPanel.java
import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JSlider;
/** * * * */ public class MineWalkerPanel extends JPanel{ private MineFieldPanel board; private JButton resetButton; private JButton displayMines; private JButton displayPath; private JButton newGame; private JButton sound; private JSlider difficulty; private boolean mineStatus; /** * Creates a new MineWalker GUI with specified width and height. * * @param width * The number of pegs in the horizontal axis. * @param height * The number of pegs in the vertical axis. */
public MineWalkerPanel(int width, int height) { // Create new MineFieldPanel with specified dimensions board = new MineFieldPanel(new MineFieldButton(), width, height);
// Create buttons and add ActionListeners resetButton = new JButton("Reset"); resetButton.addActionListener(new ResetButtonListener()); // displayMines = new JButton(mineStatus);
// Add sub-components to this main panel. this.add(board); this.add(resetButton); } /** * The ActionListener for the button to reset the game. */ private class ResetButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { board.reset(); } }
/** * Implement the ActionListener * */ private class MineFieldButton implements ActionListener { @Override public void actionPerformed(ActionEvent e) { MineFieldButton button = (MineFieldButton) e.getSource(); button.changeColor(); } }
/** * DONE: Implement the ActionListener for the button representing a peg. Changes * the color of the peg when the button is clicked. */ private class MineFieldListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { MineFieldButton button = (MineFieldButton) e.getSource(); button.changeColor(); }
} }
//MineFieldPanel.java
import java.awt.GridLayout; import java.awt.Point; import java.awt.event.ActionListener; import java.util.ArrayList;
import javax.swing.JPanel;
/** * * */ public class MineFieldPanel extends JPanel implements RandomWalkInterface{ MineFieldButton[][] mines; public MineFieldPanel(ActionListener mineFieldListener, int width, int height) { /** * setting layout & initializing array */ setLayout(new GridLayout(height, width)); mines = new MineFieldButton[height][width];
/** * adding buttons with listeners */ for (int i = 0; i
for (int j = 0; j
mines[i][j] = new MineFieldButton(); mines[i][j].addActionListener(mineFieldListener); add(mines[i][j]); } } } /** * resets all buttons */
public void reset() { for (int i = 0; i
@Override public void step() { // TODO Auto-generated method stub }
@Override public void stepEC() { // TODO Auto-generated method stub }
@Override public void createWalk() { // TODO Auto-generated method stub }
@Override public void createWalkEC() { // TODO Auto-generated method stub }
@Override public boolean isDone() { // TODO Auto-generated method stub return false; }
@Override public int getGridSize() { // TODO Auto-generated method stub return 0; }
@Override public Point getStartPoint() { // TODO Auto-generated method stub return null; }
@Override public Point getEndPoint() { // TODO Auto-generated method stub return null; }
@Override public Point getCurrentPoint() { // TODO Auto-generated method stub return null; }
@Override public ArrayList
}
?//MineFieldButton.java
import java.awt.Button; import java.awt.Color; import java.awt.Dimension;
import javax.swing.JButton;
/** * * */ public class MineFieldButton extends JButton{ private final Color[] COLORS = { Color.BLACK, Color.GREEN, Color.YELLOW, Color.ORANGE, Color.RED}; private int colorList = 0; private int nearbyMines = 0;
/** * sets defaults */ MineFieldButton() { setPreferredSize(new Dimension(20, 20)); colorList = 0; setBackground(getColor()); }
/** * resets color */ void resetColor() { colorList = 0; setBackground(getColor()); }
/** * adjusts color based on mine detection */ public void changeColor() { if (nearbyMines == 0) { colorList = 1; setBackground(getColor()); } if (nearbyMines == 1) { colorList = 2; setBackground(getColor()); } if (nearbyMines == 2) { colorList = 3; setBackground(getColor()); } if (nearbyMines >= 3) { colorList = 4; setBackground(getColor()); } }
/** * returns current color */ public Color getColor() {
return COLORS[colorList]; } /** * returns amount of nearby mines */ public Button getNearbyMines() { return null; } }
X Mine Walker Color Key Score Board 0 Nearby Mines 1 Nearby Mines 2 Nearby Mines Lives: 5 Score: 100 Exploded Mine Start Destination Hide Mines Hide Path Give Up? 10 X Mine Walker Color Key Score Board 0 Nearby Mines 1 Nearby Mines 2 Nearby Mines Lives: 5 Score: 100 Exploded Mine Start Destination Hide Mines Hide Path Give Up? 10Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started