Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Java Minesweeper

843805May 15 2006 — edited Jun 4 2006
this is my first swing app(i made it to help me better understand how this stuff works), and i have a few problems i need help fixing:
1: buttons are to large
2: a 3x3 field does not setup right
3: uses chn.util's Console IO for data input
4: want to be able to flag possilbe mines

i pretty much want my code looked through and if anyone sees anything pointless or something that might cause it to crash, let me know.
note: im still not entirely sure what main does... i just copied it from the tutorial page, if anyone can explain that ild apreciate that also
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
import java.util.ArrayList;
import chn.util.*;
import java.net.URL;


public class MineSweeper implements ActionListener
{
	int dimensions;
	JFrame MineSweeperFrame;
	JPanel MineSweeperPanel;
	JButton defaultBut;
	JButton[][] Buttons;
	JLabel[] labs;
	JLabel MineSweeperLabel;
	Location[][] Locations;
	ArrayList mineList;
	JFrame lossesFrame;
	JPanel lossesPanel;
	JLabel lossesLabel;
	static int lossCount;
	int numMines;
	
	public MineSweeper()
	{
		ConsoleIO kb = new ConsoleIO();
		numMines=0;
		dimensions=0;
		while(dimensions<=0)
		{
		 System.out.println("How many columns/rows?");
		 dimensions = kb.readInt();
		}
		while(numMines>dimensions*dimensions -1 || numMines <= 0)
		{
		 System.out.println("How many Mines?");
		 numMines = kb.readInt();
		 if(numMines>dimensions*dimensions)
		 System.out.println("Error: too many Mines.("+numMines+(numMines<dimensions*dimensions)+")");
		 if(numMines<=0)
		 System.out.println("Error: not enough Mines.("+numMines + (boolean)(numMines>=0) +")");
		}
		setMines();
		
		MineSweeperLabel = new JLabel(" ");
		MineSweeperFrame = new JFrame("My Mine Sweeper");
		MineSweeperFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		MineSweeperFrame.setSize(new Dimension(250,200));
		
		MineSweeperPanel = new JPanel(new GridLayout(dimensions+1,dimensions));
		addWidgets();	
		
		MineSweeperFrame.getRootPane().setDefaultButton(defaultBut);
		MineSweeperFrame.getContentPane().add(MineSweeperPanel, BorderLayout.CENTER);
	
		MineSweeperFrame.pack();
		MineSweeperFrame.setVisible(true);
		
		lossesLabel = new JLabel("You Loose!");
		lossesFrame = new JFrame("Game Over");
		lossesFrame.setSize(new Dimension(300,500));
		lossesPanel = new JPanel(new GridLayout(1,2));
		lossesPanel.add(lossesLabel);
		lossesFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		lossesFrame.getContentPane().add(lossesPanel, BorderLayout.CENTER);	
		lossesFrame.pack();
	}
	
	public void clearAllZeros(Location loc)//sets all buttons associated w/ a 0 to 0
	{
		if(isNoConflict(loc))
		{
			int x = loc.getX();
			int y = loc.getY();
			Buttons[x][y].setText("");
			Buttons[x][y].setEnabled(false);
			loc.setChecked(true);
			
			if(x<Locations.length-1 && !(Locations[x+1][y].isChecked()))
			clearAllZeros(Locations[x+1][y]);
			if(y<Locations.length-1 && !(Locations[x][y+1].isChecked()))
			clearAllZeros(Locations[x][y+1]);
			if(x>0 && !(Locations[x-1][y].isChecked()))
			clearAllZeros(Locations[x-1][y]);
			if(y>0 && !(Locations[x][y-1].isChecked()))
			clearAllZeros(Locations[x][y-1]);
			
			if(x<Locations.length-1 && y<Locations.length-1 && !(Locations[x+1][y+1].isChecked()))
			clearAllZeros(Locations[x+1][y+1]);
			if(x<Locations.length-1 && y>0 && !(Locations[x+1][y-1].isChecked()))
			clearAllZeros(Locations[x+1][y-1]);
			if(x>0 && y<Locations.length-1 && !(Locations[x-1][y+1].isChecked()))
			clearAllZeros(Locations[x-1][y+1]);
			if(x>0 && y>0 && !(Locations[x-1][y-1].isChecked()))
			clearAllZeros(Locations[x-1][y-1]);
			
			
			
			
			return;
		}
		return;
	 
	}
	
	public boolean isNoConflict(Location loc)
	{
		if(loc.nearMine() && !(loc.isMine()))
		{
			Buttons[loc.getX()][loc.getY()].setText(""+loc.getTNum());
			Buttons[loc.getX()][loc.getY()].setMargin(new Insets(5, 5, 5, 5));
			Locations[loc.getX()][loc.getY()].setChecked(true);
			return false;
		}
		else if(loc.isMine())
		return false;
		else return true;
		
	}
	
	
	public void setMines()//randomly creates numMines mines(locations of mines are stored in mineList)
	{
		mineList = new ArrayList();
		
		Locations = new Location[dimensions][dimensions];
		for(int i = 0; i < Locations.length;i++)
		for(int j = 0; j < Locations.length;j++)
		Locations[i][j] = new Location(i,j);
		
		Random r = new Random();
		int i = 0;
		int r1;
		int r2;
		while(i<numMines)
		{
		 r1=r.nextInt(dimensions);
		 r2=r.nextInt(dimensions);
		 
		 if(!(Locations[r1][r2].isMine()))
		 {
		 	Locations[r1][r2].setMine();
		 	mineList.add(Locations[r1][r2]);
		 	i++;
		 }
		 
		}
		
		for(int j = 0; j<Locations.length;j++)
		for(int k=0; k<Locations.length;k++)
		setMineNeighbors(j,k);
		
		
	}
	
	public void setMineNeighbors(int first, int second)
	{
	  int MineNeighbors = numMineNeighbors(first,second);
	  for(int j = 0; j<MineNeighbors;j++)
	  //if((isMine[((Location)nonMineNeighbors.get(j)).getX()][((Location)nonMineNeighbors.get(j)).getY()].isMine()))
	  {
	   Locations[first][second].numPlusPlus();
	   Locations[first][second].setNearMine();
	  }
}
	
	private class Location
	{
		private boolean mine;
		private boolean locChecked; 
		private boolean nearMine;
		private int myX;
		private int myY;
		private int myNum;
		public Location(int x, int y)
		{
			nearMine=false;
			myNum =0;
			mine=false;
			locChecked = false;
			myX=x;
			myY=y;
		}
		
		public boolean nearMine()
		{
			return nearMine;
		}
		
		public void setNearMine()
		{
			nearMine=true;
		}
		public void numPlusPlus()
		{
			myNum++;
		}
		
		public String getTNum()
		{
			if(getNum()==1)
			return "<html><font color=blue>"+getNum()+"</font></html>";
			if(getNum()==2)
			return "<html><font color=green>"+getNum()+"</font></html>";
			if(getNum()==3)
			return "<html><font color=orange>"+getNum()+"</font></html>";
			if(getNum()==4)
			return "<html><font color=red>"+getNum()+"</font></html>";
			if(getNum()==5)
			return "<html><font color=purple>"+getNum()+"</font></html>";
			if(getNum()==6)
			return "<html><font color=brown>"+getNum()+"</font></html>";
			if(getNum()==7)
			return "<html><font color=black>"+getNum()+"</font></html>";
			if(getNum()==8)
			return "<html><font color=yellow>"+getNum()+"</font></html>";
			else
			return ""+getNum();
		}
		
		public int getNum()
		{
			return myNum;
		}
		public int getX()
		{
			return myX;
		}
		
		public void setMine()
		{
			mine =true;
		}
		public boolean isMine()
		{
			return mine;
		}
		
		public int getY()
		{
			return myY;
		}
		public boolean isChecked()
		{
			return locChecked;
		}
		public void setChecked(boolean bol)
		{
			locChecked = bol;
		}
		
		public void resetStatus()
		{
			for(int i = 0; i < Locations.length; i++)
			for(int j = 0; j < Locations.length; j++)
			{
			 Locations[i][j].setChecked(false);
			 Buttons[i][j].setText("");
			}
		}
	}
	
	
	public int numMineNeighbors(int firstNum, int secondNum)
	{
		
		int num =0;
		if(firstNum < 0 || firstNum > Locations.length || secondNum < 0 || secondNum > Locations.length)
		return 0;
		
		if(!(firstNum+1 >= Locations.length))
 		if(Locations[firstNum+1][secondNum].isMine())
 		num++;
 		
		if(!(secondNum+1 >= Locations.length))
 		if(Locations[firstNum][secondNum+1].isMine())
 		num++;
 		
		if(!(secondNum-1 < 0))
 		if(Locations[firstNum][secondNum-1].isMine())
 		num++;
 		
		if(!(firstNum-1 < 0))
 		if(Locations[firstNum-1][secondNum].isMine())
 		num++;
 		
 		
 		if(!(firstNum+1 >= Locations.length || secondNum+1 >= Locations.length))
 		if(Locations[firstNum+1][secondNum+1].isMine())
 		num++;
 		
		if(!(firstNum+1 >= Locations.length || secondNum-1 < 0))
 		if(Locations[firstNum+1][secondNum-1].isMine())
 		num++;
 		
		if(!(firstNum-1 < 0 || secondNum+1 >= Locations.length))
 		if(Locations[firstNum-1][secondNum+1].isMine())
 		num++;
 		
		if(!(firstNum-1 < 0 || secondNum-1 < 0))
 		if(Locations[firstNum-1][secondNum-1].isMine())
 		num++;
 		
 		 		
 		return num;
			
	}
	
	public static void createAndShowGUI()
	{
		JFrame.setDefaultLookAndFeelDecorated(true);
		new MineSweeper();
	}
	
	public void actionPerformed(ActionEvent a)
	{
		String nums = a.getActionCommand();
		if(nums.equals("+")||nums.equals("-"))
		{
			if(nums.equals("-"))
			defaultBut.setText("+");
			for(int b = 0; b<Buttons.length; b++)
			for(int c = 0; c<Buttons.length; c++)
			{
			 Buttons[b][c].setText("");
			 Buttons[b][c].setEnabled(true);
			 Locations[b][c].setChecked(false);
			}
			setMines();
		}		
		
		String fnum="";
		String snum="";
		
		if(nums.length()>=3)
		{
		 int numf=0;
		 int numss=0;
		 fnum = nums.substring(0,nums.indexOf(" "));
		 snum = nums.substring(nums.indexOf(" ")+1,nums.length());
		 
		 /*numf = nums.substring(0,nums.indexOf(" ")).length()-1;
		 numss = nums.substring(nums.indexOf(" "),nums.length()-1).length()-1;
		 */
		 for(int i =0; i < fnum.length(); i++)
		 numf += ((((int)fnum.charAt(i))-48)*Math.pow(10,fnum.length()-i-1));
		 for(int j =0; j < snum.length(); j++)
		 numss += ((((int)snum.charAt(j))-48)*Math.pow(10,snum.length()-j-1));
		 
		
		if(Locations[numf][numss].isMine())
		{
			defaultBut.setText("-");
			for(int f =0; f<Buttons.length;f++)
		    for(int g =0; g<Buttons.length;g++)
		    Buttons[f][g].setEnabled(false);
			lossCount++;
			lossesLabel.setText("Losses: " +lossCount);
			lossesFrame.setVisible(true);
		}
		if(numf >= 0 && numss >= 0 && numf <dimensions && numss < dimensions)
		{
		 Buttons[numf][numss].setText(Locations[numf][numss].getTNum() +"");
		 Buttons[numf][numss].setMargin(new Insets(5, 5, 5, 5));
		 Locations[numf][numss].setChecked(true);
		 if(Locations[numf][numss].getNum()==0)
		 clearAllZeros(Locations[numf][numss]);
		 if(Locations[numf][numss].isMine())
		 Buttons[numf][numss].setText("�");
		}
		/*System.out.println((((int)fnum)-48) + "" + (((int)snum)-48));
		System.out.println(a.getActionCommand());*/	
		}
		int count =0;
		for(int d =0; d<Locations.length;d++)
		for(int e =0; e<Locations.length;e++)
		if(!(Locations[d][e].isChecked()))
		count++;
		System.out.println("num unchecked "+(count-numMines));
		if(count==numMines)
		{
			lossesLabel.setText("You Win!");
			lossesFrame.setVisible(true);
			System.out.println("You Win!");
		}
		
		
	}
	
	
	private void addWidgets()
	{
		
		MineSweeperPanel.add(MineSweeperLabel);
		int ammount = dimensions-2;
		for(int i = 0; i<ammount/2-1; i++)
		MineSweeperPanel.add(new JLabel(""));
		defaultBut = new JButton("+");
		defaultBut.setMargin(new Insets(5, 5, 5, 5));
		defaultBut.addActionListener(this);
		MineSweeperPanel.add(defaultBut);
		if(dimensions%2==0)
		for(int i = 0; i<ammount/2+1; i++)
		MineSweeperPanel.add(new JLabel(""));
		if(dimensions%2!=0)
		for(int i = 0; i<ammount/2+2; i++)
		MineSweeperPanel.add(new JLabel(""));
		
		Buttons = new JButton[dimensions][dimensions];
		/*for(int i = 0; i < but1.length;i++)
		{
		 for(int j = 0; j < but1.length; j++)
		 {
		 	String first="";
			String last="";
		 	for(int k = 0; k <= i;k++)//adds i+1 \0 to string first(buttons[0][0]= "\0 \0",buttons[1][1]= "\0\0 \0\0")
		  	first += "\0";
		  	for(int l = 0; l <= j;l++)//adds j+1 \0 to string last
		  	last += "\0";
		  	but1[i][j]= new JButton(first + " " + last);
		  	but1[i][j].addActionListener(this);
		  	pan1.add(but1[i][j]);
		 }
		}*/
		
		Buttons = new JButton[dimensions][dimensions];
		for(int i = 0; i < Buttons.length;i++)
		{
		 for(int j = 0; j < Buttons.length; j++)
		 {
		  Buttons[i][j] = new JButton("");
		  Buttons[i][j].setMaximumSize(new Dimension(5,5));
		  Buttons[i][j].setActionCommand(i + " " + j);
		  Buttons[i][j].addActionListener(this);
		  defaultBut.setMargin(new Insets(5, 5, 5, 5));
		  MineSweeperPanel.add(Buttons[i][j]);
		 }
		}
		
			
	}
	
	public static void main(String[] args) 
	{
       javax.swing.SwingUtilities.invokeLater(new Runnable() 
       		{
           		public void run() 
           		{
               		createAndShowGUI();
            	}
        	});

    }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 2 2006
Added on May 15 2006
20 comments
1,004 views