Game: How to make a Minesweeper in Java


Continuing the games we're doing, and teaching how to do, now we'll show you how to program the famous Minesweeper game in Java.

If you did not follow the other game made in our Java course, see:
  How to make the game Battleship in Java

Here we show the classes and game code, in the next article we will explain in detail how to program the game:

Commented and explained code of Minesweeper game in Java

How to play our Minesweeper game in Java

There is a 8x8 board, where 10 mines are located.
Each round you will provide the line number and column (i.e. numbers 1 through 8).

If there is a mine there, you lose the game.
If there is not a mine int that position, one number will appear in that location and numbers to local neighbors that you have chosen, except where there are mines.

These numbers tell you how many mines are around that place.
For example, if you choose a location, and it appears the number '2' there is because there are two mines around of that place. It is noteworthy that 'around' mean all blocks around, including the diagonals ones.

Objective: Leave the 10 fields that have free mines. That is where you deduce that there is mine, do not check, simply leave the '_' there, because when there are 10 underlines you win the game.


Minesweeper game code in Java


--> MineSweeper.java

public class MineSweeper {
    public static void main(String[] args) {
        Game game = new Game();

    }

}



--> Game.java

public class Game {
    private Board board;
    boolean finish = false;
    boolean win = false;
    int turn=0;
    
    public Jogo(){
        board = new Board();
        Play(board);
    }
    
    public void Play(Board board){
        do{
            turn++;
            System.out.println("Turn "+turn);
            board.show();
            finish = board.setPosition();
            
            if(!finish){
                board.openNeighbors();
                finish = board.win();
            }
            
        }while(!finish);
        
        if(board.win()){
            System.out.println("Congratulations, you let the 10 fields with the mines in "+turn+" turns");
            board.showMines();
        } else {
            System.out.println("Mine! You lost!");
            board.showMines();
        }
    }
}









--> Board.java

import java.util.Random;
import java.util.Scanner;

public class Board {
    private int[][] mines;
    private char[][] boardgame;
    private int Line, Column;
    Random random = new Random();
    Scanner input = new Scanner(System.in);
    
    public Board (){
        mines = new int[10][10];
        boardgame = new char[10][10];
        startMines();
        randomMines();
        fillTips();
        startBoard();
        
    }
    
    public boolean win(){
        int count=0;
        for(int line = 1 ; line < 9 ; line++)
            for(int column = 1 ; column < 9 ; column++)
                if(boardgame[line][column]=='_')
                    count++;
        if(count == 10)
            return true;
        else
            return false;                
    }
    
    public void openNeighbors(){
        for(int i=-1 ; i<2 ; i++)
            for(int j=-1 ; j<2 ; j++)
                if( (mines[Line+i][Column+j] != -1) && (Line != 0 && Line != 9 && Column != 0 && Column != 9) )
                    boardgame[Line+i][Column+j]=Character.forDigit(mines[Line+i][Column+j], 10);
        
    }
    
    public int getPosition(int Line, int Column){
        return mines[Line][Column];
    }
    
    public boolean setPosition(){
            
            do{
                System.out.print("\nLine: "); 
                Line = input.nextInt();
                System.out.print("Column: "); 
                Column = input.nextInt();
                
                if( (boardgame[Line][Column] != '_') && ((Line < 9 && Line > 0) && (Column < 9 && Column > 0)))
                    System.out.println("Field already shown");
                
                if( Line < 1 || Line > 8 || Column < 1 || Column > 8)
                    System.out.println("Choose a number between 1 and 8");
                
            }while((Line < 1 || Line > 8 || Column < 1 || Column > 8) || (boardgame[Line][Column] != '_') );
            
            if(getPosition(Line, Column)== -1)
                return true;
            else
                return false;
            
    }
    
    public void show(){
        System.out.println("\n     Lines");
        for(int Line = 8 ; Line > 0 ; Line--){
            System.out.print("       "+Line + " ");
            
            for(int Column = 1 ; Column < 9 ; Column++){
                    System.out.print("   "+ boardgame[Line][Column]);
            }
                
            System.out.println();
        }
            
        System.out.println("\n            1   2   3   4   5   6   7   8");
        System.out.println("                      Columns");
        
    }
    
    public void fillTips(){
        for(int line=1 ; line < 9 ; line++)
            for(int column=1 ; column < 9 ; column++){
                
                    for(int i=-1 ; i<=1 ; i++)
                        for(int j=-1 ; j<=1 ; j++)
                            if(mines[line][column] != -1)
                                if(mines[line+i][column+j] == -1)
                                    mines[line][column]++;
                
            }
            
    }
    
    public void showMines(){
        for(int i=1 ; i < 9; i++)
            for(int j=1 ; j < 9 ; j++)
                if(mines[i][j] == -1)
                    boardgame[i][j]='*';
        
        show();
    }
    
    public void startBoard(){
        for(int i=1 ; i<mines.length ; i++)
            for(int j=1 ; j<mines.length ; j++)
                boardgame[i][j]= '_';
    }
    
    public void startMines(){
        for(int i=0 ; i<mines.length ; i++)
            for(int j=0 ; j<mines.length ; j++)
                mines[i][j]=0;
    }
    
    public void randomMines(){
        boolean raffled;
        int Line, Column;
        for(int i=0 ; i<10 ; i++){
            
            do{
                Line = random.nextInt(8) + 1;
                Column = random.nextInt(8) + 1;
                
                if(mines[Line][Column] == -1)
                    raffled=true;
                else
                    raffled = false;
            }while(raffled);
            
            mines[Line][Column] = -1;
        }
    }
}

15 comments:

Shivam Kumar said...

Nice One visit this minesweeper game example

Unknown said...

An online multiplayer mode was definitely true on my TODO list for this game. Infact, I was more into MSN on the flags for a while, but hated that it was still offline, and thus began this project.
how to play minesweeper like a pro

Unknown said...

An online multiplayer mode was definitely true on my TODO list for this game. Infact, I was more into MSN on the flags for a while, but hated that it was still offline, and thus began this project.
how to play minesweeper like a pro

Unknown said...

When i plug this into my IDE it doesn't show the table or anything. it just says "BUILD SUCCESSFUL..." Is there something I need to add to make it work?

Unknown said...

When I plug this code into my IDE and run it nothing shows up. All it shows is "BUILD SUCCESSFUL..." Is there something I need to add or change about the code to make it work?

Unknown said...

thanks for sharing amazing information

how to play minesweeper

Anonymous said...

Does this code playable for all java compilers?

Anonymous said...

mine doesn't work

Anonymous said...

I tried copying and pasting the code, but it does not run. Are there any possible mistakes or missing code here?

Anonymous said...

Any possible mistakes with this code? It does not run for me

Unknown said...

Change Jogo constructor by Game.

Unknown said...

Change Jogo constructor by Game.

Unknown said...

I see what you mean. The problem is the public class Jogo. I don't know where Jogo comes from

Unknown said...

The problem is the public class Jogo

Anonymous said...

You need to change Jogo to Game in the Game class