Building mine sweeper Java application using ant

This example assumes you have java jdk and ant installed on your system and you are using linux or mac.

1. Create minesweep project directory and src directory

mkdir minesweep
mkdir minesweep/src
mkdir minesweep/src/mine
cd minesweep/src/mine

2. Create the java source file for the minesweep app in minesweep/src/mine/
MineSweep.java

package mine;
public class MineSweep {
	public static void main(String args[])
	{
		MineField mf = new MineField();
	      final int SIZE = 300;
	      mf.setSize(SIZE, SIZE);
	      mf.setVisible(true);
	}
}

Border.java

package mine;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;

import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;

public class Border extends JFrame{
	public int ROWS;
	public int COLS;
	public int GAP=2;
	public JPanel mainPanel;   
	public JPanel[][] panel;
	public JLabel[][] panelLabel;
	
	public final int ESAYR=6;
	public final int ESAYC=8;
	public final int MEDIANR=8;
	public final int MEDIANC=12;
	public final int HARDR=12;
	public final int HARDC=16;
	
	// Creates a menubar for a JFrame	      

	   
	public JMenuBar menuBar = new JMenuBar();
	   // Define and add two drop down menu to the menubar	   
	public JMenu mainMenu = new JMenu("Menu");
	public JMenu levelMenu = new JMenu("Level");
	   
	   // Create and add simple menu item to one of the drop down menu	   
	public JMenuItem newAction = new JMenuItem("New Game");	   	   
	public JMenuItem exitAction = new JMenuItem("Exit");
	   
	   	   
	   // Create and add CheckButton as a menu item to one of the drop down	   
	   // menu	   
	   
	public JCheckBoxMenuItem esayLevel = new JCheckBoxMenuItem("esay");	   
	public JCheckBoxMenuItem medianLevel = new JCheckBoxMenuItem("median");	   
	public JCheckBoxMenuItem hardLevel = new JCheckBoxMenuItem("hard");
	
	public Color color1 = Color.WHITE;
	public Color color2 = Color.GRAY;
	public Color color3 = Color.RED;
	public Color color4 = Color.GREEN;
	
	public Border(String name)
	{
		super(name);
		ROWS=ESAYR;
		COLS=ESAYC;
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(400,300);
	}
	
	
	 // Sets the game level.
	 // @param rows, the number of rows.
	 // @param cols, the number of columns.
	public void setLevel(int rows, int cols)
	{
		ROWS=rows;
		COLS=cols;
	}
	
	
	 // Creates the Border.
	 // @param rows, the number of rows.
	 // @param cols, the number of columns.
	 // @param gap, the gap between rows and columns.
	public void createBorder()
	{
		//ROWS=ESAYR;
		//COLS=ESAYC;
		panelLabel=new JLabel[ROWS][COLS];
		mainPanel = new JPanel(new GridLayout(ROWS, COLS, GAP, GAP));   
		panel = new JPanel[ROWS][COLS];
		add(mainPanel);
		
		for(int r=0; r<ROWS; r++)
		{
			for(int c=0; c<COLS; c++)
			{
				panel[r] = new JPanel();
				mainPanel.add(panel[r]);
			}
		}
	}
	

	
	  
	 //@return the number of panels, meanly the size of border.
	public int numofPanels()
	{
		return ROWS*COLS;
	}
	

	 // @param r the row index.
	 // @param c the column index.
	 // @return true if the indexes of row and column are within the Border range.
	public boolean isInRange(int r, int c)
	{
		if(r>=0 && r<=ROWS-1 && c>=0 && c<=COLS-1)
			return true;
		else
			return false;	
	}
}

MineField.java

package mine;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;

import javax.swing.*;
public class MineField extends Border implements MouseListener, ActionListener
{	   
   private final String MINE="bomb";
  
   private int numofmines;
   private int unveiledSpot;
   private int totalSafeSpot;   
   
   
    // Constructor
   public MineField()
   {
      super("MineSweep");
      
      settingMenuBar();
      initialize();
   }
   
   private void initialize()
   {    
	   createBorder();
	   mainPanel.setBackground(color2);
	   
	   //numofmines is 10% of the number of grids.
	   numofmines=numofPanels()/10;
	
	   unveiledSpot=0;
	   totalSafeSpot=numofPanels()-numofmines;

	   createMineField();
	   
	   //Generating random mines.
	   settingMines();
	   settingHints();
	   
	   //unveil();
	   //System.out.println("number of mines: " +numofmines);
	   
   }
   

   
    // Sets the menu bar.
   private void settingMenuBar()
   {
	   menuBar.setBackground(color2);
	   
	   esayLevel.setText("Back Yard");
	   medianLevel.setText("Front Line");
	   hardLevel.setText("Battle Field");
	   // Add the menubar to the frame   
	   setJMenuBar(menuBar);	   

	   //add the main menu.
	   menuBar.add(mainMenu);
	   
	   newAction.addActionListener(this);
	   exitAction.addActionListener(this);
	   esayLevel.addActionListener(this);
	   medianLevel.addActionListener(this);
	   hardLevel.addActionListener(this);
	   
	   newAction.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));
       exitAction.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, InputEvent.CTRL_MASK));
	   
	   esayLevel.setSelected(true);
	   
	   //add menu items.
	   mainMenu.add(newAction);
	   mainMenu.add(levelMenu);
	   mainMenu.addSeparator();
	   mainMenu.add(exitAction);
	   
	   levelMenu.add(esayLevel);
	   levelMenu.add(medianLevel);
	   levelMenu.add(hardLevel);
 
   }
   
   
    // Setting the hints around a grid, how many mines are around a grid.
   private void settingHints()
   {
	   //JLabel label;	
	   for(int r=0; r<ROWS; r++)	
	   {		
		   for(int c=0; c<COLS; c++)		
		   {
			   if(!isMine(panelLabel[r]))
			   {
				   panelLabel[r].setText(Integer.toString(findAdjacentMines(r,c)));
				   panelLabel[r].setVisible(false);
			   }
		   }	
	   }   
   }
   
   
    // @param row 
	// @param col
    // @return the number of adjacent mines.
    // Find the number of mines around a grid.
   private int findAdjacentMines(int row, int col)
   {
	   int adjacentMines=0;
	   int r,c;
	   
	   //upper left
	   r=row-1;c=col-1;
	   adjacentMines=adjacentMines+isAMine(r,c);
	   
	   //upper middle
	   r=row-1;c=col;
	   adjacentMines=adjacentMines+isAMine(r,c);
	   
	   //upper right
	   r=row-1;c=col+1;
	   adjacentMines=adjacentMines+isAMine(r,c);
	   
	   //left
	   r=row;c=col-1;
	   adjacentMines=adjacentMines+isAMine(r,c);
	   
	   //right
	   r=row;c=col+1;
	   adjacentMines=adjacentMines+isAMine(r,c);
	   
	   //lower left
	   r=row+1;c=col-1;
	   adjacentMines=adjacentMines+isAMine(r,c);
	   
	   //lower middle
	   r=row+1;c=col;
	   adjacentMines=adjacentMines+isAMine(r,c);
	   
	   //lower right
	   r=row+1;c=col+1;
	   adjacentMines=adjacentMines+isAMine(r,c);
	   
	   return adjacentMines;
   }
   
   
    // Checking if a grid is mined.
   private int isAMine(int r, int c)
   {
	   int ismine=0;
	   if(isInRange(r,c))
	   {
		   if(isMine(panelLabel[r]))
			   ismine=1;
		   return ismine;
	   }
	   else
		   return ismine;
   }
   
   
    // Checking if a grid is mined.
   private boolean isMine(JLabel label)
   {
	   return label.getText().equals(MINE);
   }
   
   
    // Setting up mines in the mine field.
   private void settingMines() 
   {
	   Random ran=new Random();
	   boolean go=true;
	   for(int i=0; i<numofmines;i++)	   
	   {	   
		   int r=0, c=0;//row, col
		   go=true;
		   r=ran.nextInt(ROWS);	    		
		   c=ran.nextInt(COLS);	
		   while(go)	    	
		   {	
			   r=ran.nextInt(ROWS);	    		
			   c=ran.nextInt(COLS);	    		
			   if(isMine(panelLabel[r]))   
				   go=true;
			   else
			   {
				   go=false;
				   panelLabel[r].setText(MINE);
				   panelLabel[r].setVisible(false);
			   }
		   }
	   }	      
   }
   
   
   
    //Creates the mine field,add labels and mouselistener.
   private void createMineField()
   {
	   
	   for(int i=0; i<ROWS; i++)
	      {
	    	  for(int j=0; j<COLS; j++)
	    	  {
	    		  panelLabel[i][j] = new JLabel("");
	    		  panel[i][j].add(panelLabel[i][j]);
	              panel[i][j].addMouseListener(this);
	    	  }
	      }
   }
   
   
    // Unveil everything in the mine filed.
   private void unveil()
   {
	   for(int r=0; r<ROWS; r++)
	   {
		   for(int c=0; c<COLS; c++)
		   {
			   if(panelLabel[r].getText().equals(MINE))
					panel[r].setBackground(color3);
				else
					panel[r].setBackground(color1);
				
				panelLabel[r].setVisible(true);
		   }
	   }
   }
   
   private void unveilMines(Color color)
   {
	   for(int r=0; r<ROWS; r++)
	   {
		   for(int c=0; c<COLS; c++)
		   {
			   if(panelLabel[r].getText().equals(MINE))
			   {
				   panel[r].setBackground(color);
				   panelLabel[r].setVisible(true);
			   }
		   }
	   }
   }
   
   public int numofBomb()
   {
	   int num=0;
	   for(int r=0; r<ROWS; r++)
	   {
		   for(int c=0;c<COLS;c++)
		   {
			   if(isMine(panelLabel[r]))
				   num=num+1;
		   }
	   }
	   return num;
   }
   
   public static void main(String[] arguments)
   {
      MineField mf = new MineField();
      mf.setVisible(true);  
   }

@Override
public void mouseClicked(MouseEvent e) {
	// TODO Auto-generated method stub
	JPanel p=(JPanel) e.getComponent();
	JLabel label=(JLabel) p.getComponent(0);
	
	if(label.getText().equals(MINE))
		unveilMines(color3);
	else
	{
		p.removeMouseListener(this);
		p.setBackground(color1);
		unveiledSpot++;
		if(unveiledSpot==totalSafeSpot)
			unveilMines(color4);
	}
	
	label.setVisible(true);
}

@Override
public void mouseEntered(MouseEvent e) {
	// TODO Auto-generated method stub
	
}

@Override
public void mouseExited(MouseEvent e) {
	// TODO Auto-generated method stub
	
}

@Override
public void mousePressed(MouseEvent e) {
	// TODO Auto-generated method stub
	
}

@Override
public void mouseReleased(MouseEvent e) {
	// TODO Auto-generated method stub
	
}


@Override
public void actionPerformed(ActionEvent e) {
	// TODO Auto-generated method stub
	
	if(e.getSource() == this.newAction)
	{
		if(esayLevel.isSelected())
		{
			this.remove(mainPanel);
			setLevel(ESAYR,ESAYC);
			initialize();
			this.setSize(400, 300);
		}
		else if(medianLevel.isSelected())
		{
			this.remove(mainPanel);
			setLevel(MEDIANR,MEDIANC);
			initialize();
			this.setSize(700, 500);
		}
		else
		{
			this.remove(mainPanel);
			setLevel(HARDR,HARDC);
			initialize();
			this.setSize(1000, 700);
		}
	}
	else if(e.getSource() == this.exitAction)
	{
		this.dispose();
	}
	else if(e.getSource() == this.esayLevel)
	{
		this.medianLevel.setSelected(false);
		this.hardLevel.setSelected(false);
	}
	else if(e.getSource() == this.medianLevel)
	{
		this.esayLevel.setSelected(false);
		this.hardLevel.setSelected(false);
	}
	else if(e.getSource() == this.hardLevel)
	{
		this.esayLevel.setSelected(false);
		this.medianLevel.setSelected(false);
	}
	
}

}

3. Create the build.xml in minesweep/

<project name="MineSweep" basedir="." default="main">
    <property name="src.dir"     value="src"/>
    <property name="build.dir"   value="build"/>
    <property name="classes.dir" value="${build.dir}/classes"/>
    <property name="jar.dir"     value="${build.dir}/jar"/>
    <property name="main-class"  value="mine.MineSweep"/>

    <target name="clean">
        <delete dir="${build.dir}"/>
    </target>

    <target name="compile">
        <mkdir dir="${classes.dir}"/>
        <javac srcdir="${src.dir}" destdir="${classes.dir}"/>
    </target>

    <target name="jar" depends="compile">
        <mkdir dir="${jar.dir}"/>
        <jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}">
            <manifest>
                <attribute name="Main-Class" value="${main-class}"/>
            </manifest>
        </jar>
    </target>

    <target name="run" depends="jar">
        <java jar="${jar.dir}/${ant.project.name}.jar" fork="true"/>
    </target>

    <target name="clean-build" depends="clean,jar"/>

    <target name="main" depends="clean,run"/>

</project>

4. Try the commands below in minesweep/, each of these command corresponds to one of the targets specified in the build.xml

ant -f build.xml
This command will execute all the targets specified in the build.xml

ant clean
This command will execute the clean target in the build.xml, it will delete the build directory if it exist.

ant compile
This command will execute the compile target in the build.xml, it will create directories build/classes/ with .class files

ant jar
This command will create runnable jar file in the directory build/jar/

ant run
This command will run the minesweep app, it will make sure ant jar was executed first

ant clean-build
This command will execute ant clean and ant jar

ant main
This command will execute ant clean and ant run

Search within Codexpedia

Custom Search

Search the entire web

Custom Search