Question

java minesweeper

need help writing a JAVA Program: a playable version of Minesweeper. It needs to be

● Playable by one player

● Show the board before asking the player for input

● Instruct the player on how to play at the start of the game

● Implement the standard rules of Minesweeper

● Make the bomb count ~15% of the total number of spaces

● Allow the user to specify the game board dimensions at the start of the game

 

I can: ● Use any objects in the java standard library (java.whatever) ● Allow non-solvable versions of the game to be generated (just like in the original game) ● Go as far above and beyond the requirements


0 0
Add a comment Improve this question Transcribed image text
Answer #1
import acm.graphics.*;
import acm.program.*;
import acm.util.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class Minesweeper extends GraphicsProgram implements MouseMotionListener {
     
    /** Number of bricks per row */
    public static  int TILE_COLUMNS= 10;
    /** Number of rows of bricks, in range 1..10. */
    public static  int TILE_ROWS= 10;
    /** Width of a brick */
    public static int TILE_SIDE=40;
    /** Width of the game display (al coordinates are in pixels) */
    public static final int GAME_WIDTH= TILE_COLUMNS*TILE_SIDE;
    /** Height of the game display */
    public static final int GAME_HEIGHT= TILE_ROWS*TILE_SIDE;
    public static char Mines[][]=new char [TILE_COLUMNS] [TILE_ROWS];
    public static boolean TILE_BLOCK=false;
    public static boolean GAME_LOSS, GAME_WIN;
    /** Mine Number. Default setting - 10% of squares */
    public static final int MINE_NUMBER= (int) (TILE_COLUMNS*TILE_ROWS/10);
     /** rowColors[i] is the color of row i of bricks */
    private static final Color[] TileColors= {Color.white, Color.blue, Color.green, Color.red, new Color (128,0,128),Color.black,
    new Color (128,0,0), new Color (64224208), new Color (128,128,128)};
     
    /** random number generator */
    private RandomGenerator rgen= new RandomGenerator();
    /** Run the program as an application.
      */
    public static void main(String[] args) {
        String[] sizeArgs= {"width=" + GAME_WIDTH, "height=" + GAME_HEIGHT};
        new Minesweeper().start(sizeArgs);
    }
     
    /** Run the Minesweeper program. */
    public void run() {
        setup();
    }
     
    /** Set Up all the components of Minesweeper */
    public void setup () {
        createBricks();
        MineGenerator();
        NumberGenerator();
        addMouseListeners();
    }
     
    /** Creates the set of Bricks for the Minesweeper board */
    private void createBricks () {
        for (int i=0;i<TILE_COLUMNS;i++) {
            for (int j=0;j<TILE_ROWS;j++) {
                Tile tile=new Tile (i*TILE_SIDE, j*TILE_SIDE, TILE_SIDE,TILE_SIDE);
                tile.setColor (new Color (100,100,100));
                tile.setRaised (true);
                tile.setFilled (true);
                add(tile);
            }
        }
    }
     
    /** Randomly generate mines throughtout the board */
    private void MineGenerator () {
        int i=0;
        while (i<MINE_NUMBER) {
            int x=rgen.nextInt(0,TILE_COLUMNS-1);
            int y=rgen.nextInt(0,TILE_ROWS-1);
            if (Mines[x][y]!='x') {
                Mines[x][y]='x';
                i++;
            }
        }           
    }
     
    /** Generates the numbers on each of the tiles throughout the board. Each number denoted the number of mines surrounding
      * the tile. 0 is not displayed. */
    private void NumberGenerator () {
        for (int i=0;i<TILE_COLUMNS;i++) {
            for (int j=0;j<TILE_ROWS;j++) {
                if (Mines[i][j]!='x'
                    Mines [i][j]=(char) (CountSurround (i,j)+48);
                if (Mines[i][j]=='0')
                    Mines[i][j]=' ';
            }
        }
    }
     
    /** Counts the mines surrounding the Tile at [i,j] */
    private int CountSurround (int i, int j) {
        int count=0;
        if (i+1!=TILE_COLUMNS && Mines [i+1][j]=='x')
            count++;
        if (i+1!=TILE_COLUMNS &&  j+1!=TILE_ROWS && Mines [i+1][j+1]=='x')
            count++;
        if (i-1!=-1 && j+1!=TILE_ROWS && Mines [i-1][j+1]=='x')
            count++;
        if (i+1!=TILE_COLUMNS && j-1!=-1 && Mines [i+1][j-1]=='x')
            count++;
        if (i-1!=-1 && j-1!=-1 && Mines [i-1][j-1]=='x')
            count++;
        if (i-1!=-1 &&  Mines [i-1][j]=='x')
            count++;
        if (j+1!=TILE_ROWS &&  Mines [i][j+1]=='x')
            count++;
        if (j-1!=-1 &&  Mines [i][j-1]=='x')
            count++;
        return count;
    }
   
    /** Procedure that is run when mouse is clicked */
    public void mouseClicked(MouseEvent e) {
        if (GAME_LOSS==false && GAME_WIN==false) {
            GPoint p= new GPoint(e.getPoint());
            if (SwingUtilities.isRightMouseButton(e)) {
                FlagTile (getTileAt (p));
            }
            else if (SwingUtilities.isLeftMouseButton(e)) {
                GLabel label=getLabelAt(p);
                if (label!=null && label.getLabel()==""+'#')
                    remove (label);
                PressTile (getTileAt(p), true);
            }
        }
    }
      
    /** Flag the Tile t */
    public void FlagTile (Tile t) {
        if (t.flagged==false) {
            t.flagged=true;
            t.setColor (new Color (220,220,220));
            GLabel label=new GLabel (""+'#', t.getLocation().getX(),t.getLocation().getY()+TILE_SIDE);
            label.setFont(new Font("Lucida Grande", Font.BOLD, 3*TILE_SIDE/4));
            label.move((TILE_SIDE-label.getWidth())/2 , -2*(TILE_SIDE-label.getHeight()));
            label.setColor (Color.red);
            add (label);
        }
        else {
            t.flagged=false;
            t.setColor (new Color (100,100,100));
            remove (getLabelAt(t.getLocation()));
        }
    }
         
    /** Press the Tile t */
    public void PressTile (Tile t, boolean clearblanks) {
        t.setColor (new Color (200,200,200));
        char c=LabelPrinter (t.getLocation());
        if (c=='x') {
            t.setColor (Color.red);
            BlockAllTiles();
        }
        if (c==' ' && clearblanks==true)
            clearBlanks ((int) t.getLocation().getX()/TILE_SIDE,(int)t.getLocation().getY()/TILE_SIDE);
        t.setRaised(false);
        if (isRemaining()==false)
            WinSign();
    }
      
    /** Blocks all tiles when Mine is hit */
    public void BlockAllTiles() {
        GAME_LOSS=true;
        for (int i=0;i<TILE_COLUMNS;i++) {
            for (int j=0;j<TILE_ROWS;j++) {
                Tile t= getTileAt(i,j);
                t.setColor (Color.red);
            }
        }
    }
     
    /** Clear surrounding blank tile if a blank tile is pressed */        
    public void clearBlanks(int i, int j) {
        if (i==-1 || i==TILE_COLUMNS || j==-1 || j==TILE_ROWS  || getTileAt(i,j).isRaised()==false
            return;
        if (Mines [i][j]!=' ') {
            PressTile (getTileAt(i,j), false);
            return;
        }
        PressTile (getTileAt(i,j), false);
        for (int p=-1;p<=1;p++) {
            for (int q=-1;q<=1;q++) {
                clearBlanks (i+p,j+q);
            }
        }
    }
     
    /** Prints the appropriate Tile label at Gpoint p and returns the character printed */
    public char LabelPrinter (GPoint p) {
        int x=(int) (p.getX()/TILE_SIDE);
        int y=(int) (p.getY()/TILE_SIDE);
        GLabel label=new GLabel (""+Mines[x][y], x*TILE_SIDE,(y+1)*TILE_SIDE);
        label.setFont(new Font("Lucida Grande", Font.BOLD, 3*TILE_SIDE/4));
        label.move((TILE_SIDE-label.getWidth())/2 , -2*(TILE_SIDE-label.getHeight()));
        if (49<=Mines [x][y] && 57>=Mines[x][y])
            label.setColor (TileColors[Mines[x][y]-48]);
        add (label);
        return Mines[x][y];
    }
     
    /** Prints the Win Symbol*/
    public void WinSign() {
        for (int i=0;i<TILE_COLUMNS;i++) {
            for (int j=0;j< TILE_ROWS;j++) {
                Tile t=getTileAt (i,j);
                t.setColor(Color.green);
                if (t.isRaised()) {
                    GLabel g=getLabelAt (t.getLocation());
                    if (g!=null)
                        g.setLabel ("W");
                    else {
                        g=new GLabel ("W",t.getLocation().getX(),t.getLocation().getY()+TILE_SIDE);
                        g.setFont(new Font("Lucida Grande", Font.BOLD, 3*TILE_SIDE/4));
                        g.move((TILE_SIDE-g.getWidth())/2 , -2*(TILE_SIDE-g.getHeight()));
                        add (g);
                    }
                    g.setColor (Color.black);
                }
            }
        }
    }
     
    /** Returns true if there are pressable tiles remaining and false otherwise */
    public boolean isRemaining() {
        for (int i=0;i<TILE_COLUMNS;i++) {
            for (int j=0;j< TILE_ROWS;j++) {
                Tile t=getTileAt(i,j);
                if (t.isRaised()==true) {
                    if (Mines [i][j]=='x')
                        continue;
                    else
                        return true;
                }
            }
        }
        GAME_WIN=true;
        return false;
    }
 
    /** Returns the tile at GPoint p */
     public Tile getTileAt (GPoint p) {
         int x=((int)(p.getX()/TILE_SIDE))*TILE_SIDE+1;
         int y=((int)(p.getY()/TILE_SIDE))*TILE_SIDE+1;
         GObject g=getElementAt (x,y);
         return (Tile)g;
     }
      
     /** Returns the tile at the coordinate i,j */
     public Tile getTileAt (int i, int j) {
         int x=i*TILE_SIDE+1;
         int y=j*TILE_SIDE+1;
         GObject g=getElementAt (x,y);
         return (Tile)g;
     }
      
     /** Returns the label at the coordinate i,j.Null, if there is none */
      public GLabel getLabelAt (int i, int j) {
         int x=i*TILE_SIDE+(TILE_SIDE/2);
         int y=j*TILE_SIDE+(TILE_SIDE/2);
         GObject g=getElementAt (x,y);
         if (g instanceof GLabel)
             return (GLabel)g;
         return null;
      }
       
      /** Returns the label at the Point p.Null, if there is none */
      public GLabel getLabelAt (GPoint p) {
         int x=((int)(p.getX()/TILE_SIDE))*TILE_SIDE+(TILE_SIDE/2);
         int y=((int)(p.getY()/TILE_SIDE))*TILE_SIDE+(TILE_SIDE/2);
         GObject g=getElementAt (x,y);
         if (g instanceof GLabel)
             return (GLabel)g;
         return null;
      }
}
 
/** An instance is a Brick */
class Tile extends G3DRect {
    public boolean flagged;
    /** Constructor: a new brick with width w and height h*/
    public Tile(double w, double h) {
           super (w,h);
           flagged=false;
    }
     
    /** Constructor: a new brick at (x,y) with width w and height h*/
    public Tile(double x, double y, double w, double h) {
             super (x,y,w,h);
             flagged=false;
    }
}


answered by: codegates
Add a comment
Know the answer?
Add Answer to:
java minesweeper
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Please program this in Visual Basic 6. You have chosen to create an electronic version of the sliding tile puzzle game....

    Please program this in Visual Basic 6. You have chosen to create an electronic version of the sliding tile puzzle game. The object of the game is to slide the tiles so that they end up in the required order. The images shown below are examples of the two different versions of this puzzle (numeric and graphical) Puzzle Board-Numeric Puzzle Board-Graphical File Options Help Elapsed Time File Options Help Elapsed Time 00:02:12 00:04:20 5 6 7 8 9 10 11...

  • I need help with my programming assignment. The language used should be java and the algorithm...

    I need help with my programming assignment. The language used should be java and the algorithm should use search trees so that you play against the computer and he chooses the best move. The tree should have all possibilities on the leaves and you could use recursion to so that it populates itself. The game can be a 3*3 board (no need the make it n*n). Please put comments so that I can understand it. Thanks The game of ‘Walls’...

  • War—A Card game Playing cards are used in many computer games, including versions of such classic...

    War—A Card game Playing cards are used in many computer games, including versions of such classics as solitaire, hearts, and poker. War:    Deal two Cards—one for the computer and one for the player—and determine the higher card, then display a message indicating whether the cards are equal, the computer won, or the player won. (Playing cards are considered equal when they have the same value, no matter what their suit is.) For this game, assume the Ace (value 1) is...

  • JAVA Only Help on the sections that say Student provide code. The student Provide code has...

    JAVA Only Help on the sections that say Student provide code. The student Provide code has comments that i put to state what i need help with. import java.util.Scanner; public class TicTacToe {     private final int BOARDSIZE = 3; // size of the board     private enum Status { WIN, DRAW, CONTINUE }; // game states     private char[][] board; // board representation     private boolean firstPlayer; // whether it's player 1's move     private boolean gameOver; // whether...

  • Java Constructor and method

    Player Class Specification The Player class represents a player that will play a simple game. In this game, a player can play the number 0, 1, or 2. The Player class contains the following four fields: private String name; private int play; private int [] tally; private StringBuffer history; The Player class contains the following 2 constructors and 5 methods that you must implement: 1. Constructor with String parameter – If the argument is null, throw the IllegalArgumentException with the...

  • How to make a reversi/othello game in JAVA? Ideally with multiple classes and without GUI You...

    How to make a reversi/othello game in JAVA? Ideally with multiple classes and without GUI You are implementing a strategy board game played by two players, Black and White. It is played on an N by N board. The winner is the player who has more discs of his color than his opponent at the end of the game. This will happen when neither of the two players has a legal move or there are no spaces left on the...

  • I have to use java programs using netbeans. this course is introduction to java programming so...

    I have to use java programs using netbeans. this course is introduction to java programming so i have to write it in a simple way using till chapter 6 (arrays) you can use (loops , methods , arrays) You will implement a menu-based system for Hangman Game. Hangman is a popular game that allows one player to choose a word and another player to guess it one letter at a time. Implement your system to perform the following tasks: Design...

  • The game must be done in java in Netbeans 1. Write a Guessing Game. In the...

    The game must be done in java in Netbeans 1. Write a Guessing Game. In the game, the user will guess a number. a. In the StartGui, the use needs to choose a difficulty level: Easy or Difficult. If easy level is selected, the user will guess between 1 and 10. If difficult level is selected, the user will guess 1 and 100. Then the user will click Start button and go to the GamePage. b. In the GamPage, the...

  • PLEASE INCLUDE SAW-PROMPTS FOR 2 PLAYERS NAMES(VALIDATE NAMES). SHOW MENU (PLAYER MUST SELECT FROM MENU B4...

    PLEASE INCLUDE SAW-PROMPTS FOR 2 PLAYERS NAMES(VALIDATE NAMES). SHOW MENU (PLAYER MUST SELECT FROM MENU B4 THE GAME STARTS 1=PLAY GAME, 2=SHOW GAME RULES, 3=SHOW PLAYER STATISTICS, AND 4=EXIT GAME WITH A GOODBYE MESSAGE.) PLAYERS NEED OPTION TO SHOW STATS(IN A DIFFERNT WINDOW-FOR OPTION 3)-GAME SHOULD BE rock, paper, scissor and SAW!! PLEASE USE A JAVA GRAPHICAL USER INTERFACE. MUST HAVE ROCK, PAPER, SCISSORS, AND SAW PLEASE This project requires students to create a design for a “Rock, Paper, Scissors,...

  • Advanced Object-Oriented Programming using Java Assignment 4: Exception Handling and Testing in Java Introduction -  This assignment...

    Advanced Object-Oriented Programming using Java Assignment 4: Exception Handling and Testing in Java Introduction -  This assignment is meant to introduce you to design and implementation of exceptions in an object-oriented language. It will also give you experience in testing an object-oriented support class. You will be designing and implementing a version of the game Nim. Specifically, you will design and implement a NimGame support class that stores all actual information about the state of the game, and detects and throws...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT