Minesweeper assignment getSource()

  • (2 Pages)
  • +
  • 1
  • 2

21 Replies - 10863 Views - Last Post: 13 October 2011 - 04:40 AM Rate Topic: -----

#1 prosper   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 11-October 11

Minesweeper assignment getSource()

Posted 11 October 2011 - 09:14 PM

I'm fairly new to programming and am having trouble getting my code to work. I essentially have to make minesweeper but flags are not a requirement (basically just have adjacent squares to the square clicked clear if there isn't a bomb). I made an initial menu to get row and column variables from the user and my basic logic was make three arrays, one for the buttons, a second boolean array to say if a bomb is present in each square, and a third int array that holds the number of adjacent bombs. The code isn't quite finished, but I feel like it should run with what I have and I keep getting a getSource() null pointer exception and I'm not sure exactly what it is coming from. Like I said, I am fairly new to programming and comments on any of the program will be greatly appreciated.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;

public class Project1Minesweeper extends JFrame{

	private static int width = 800;
	private static int height = 800;
	private int bombsplaced = 0;
	Container pane;
	Container gamepane;
	private JLabel rowsL, columnsL, bombsL;
	private JTextField rowsTF, columnsTF, bombsTF;	
	private JButton startB, exitB;
	private StartButtonHandler startBhandler;
	private ExitButtonHandler exitBhandler;
	private ButtonHandler Bhandler;	
	JButton board [][];
	Boolean bomb [][];
	int surroundings [][];
	
	int rows , columns, bombs;
	
	public Project1Minesweeper()
	{
		setTitle("Minesweeper v.11 by Steven Wirth");
		setSize(width,height);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		pane = getContentPane();
		pane.setLayout(new GridLayout(4,2));
				
		rowsL = new JLabel("Enter the number of rows: ", SwingConstants.CENTER);
		columnsL = new JLabel("Enter the number of columns: ", SwingConstants.CENTER);
		bombsL = new JLabel("Enter the number of bombs: ", SwingConstants.CENTER);
		startB = new JButton("Start Game!");
		exitB = new JButton("Exit");
		
		rowsTF = new JTextField("10",10);
		columnsTF = new JTextField("10",10);
		bombsTF = new JTextField("10",10);
		
		pane.add(rowsL);
		pane.add(rowsTF);
		pane.add(columnsL);
		pane.add(columnsTF);
		pane.add(bombsL);				
		pane.add(bombsTF);
		pane.add(startB);
		pane.add(exitB);
		
		startBhandler = new StartButtonHandler();
		exitBhandler = new ExitButtonHandler();
		Bhandler = new ButtonHandler();
		startB.addActionListener(startBhandler);
		exitB.addActionListener(exitBhandler);
		
		setVisible(true);
		
	}
	public static void main(String[] args) {
		new Project1Minesweeper();

	}
	
	private class StartButtonHandler implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) 
		{
			GameStart();
			
		}
		
		
		
	}
	
	private class ExitButtonHandler implements ActionListener {
		public void actionPerformed(ActionEvent arg0)
		{
			System.exit(0);
		}

		
	}
	
	
	public void GameStart()
	{
		
		
		
		rows = Integer.parseInt(rowsTF.getText());
		columns = Integer.parseInt(columnsTF.getText());
		bombs = Integer.parseInt(bombsTF.getText());
		Random randomGenerator =new Random();
		
		
		JButton board [][] = new JButton[rows][columns];
		Boolean bomb [][] = new Boolean[rows][columns];
		int surroundings [][] = new int[rows][columns];
										
		setVisible(false);
		pane.removeAll();	
		
		setTitle("Minesweeper!!");
		setSize(800,800);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		pane.setLayout(new GridLayout(rows, columns));

		
//Draws all the buttons on the board		
		for (int i = 0; i< columns ; i++){
			for (int j = 0 ; j < rows ; j++){
				board[i][j] = new JButton(); 
				pane.add(board[i][j]);				
				board[i][j].addActionListener(Bhandler);
			}
			
		}
		
//Makes all the spaces on the board "false" for bombs		
		for (int i = 0; i< columns ; i++){
			for (int j = 0 ; j < rows ; j++){
				bomb[i][j] = false; 
				
			}
			
		}
//Makes the value of all the spaces in the surroundings array 0
		for (int i = 0; i< columns ; i++){
			for (int j = 0 ; j < rows ; j++){
				surroundings[i][j] = 0; 
				
			}
			
		}
		
//Adds bombs to the board in random spaces
		while (bombsplaced<=bombs)
		{
			int RandomHeight = randomGenerator.nextInt(columns-1);
			int RandomWidth = randomGenerator.nextInt(rows-1);
			
			if (bomb[RandomWidth][RandomHeight] == false)
			{
				bomb[RandomWidth][RandomHeight] = true;
				bombsplaced++;
			}
			
			
		}

//Checks the eight squares around each button and assigns that number to that square so that it can be checked later		
		for (int i = 0; i< columns ; i++){
			for (int j = 0 ; j < rows ; j++){
				for(int x=(i-1); x<= (i + 1); x++)
				{
					for(int y=(j-1); y <=(j+1); y++)
					{
						//Stops the adjacent squares from clearing if the entry is out of bounds
						if(x<0 || x>=columns || y<0 || y>=rows)
						{
							break;
						}
						
						else if (bomb[x][y]==true)
						{
							++surroundings[i][j];
						}
				
						
				}
			}
			}
		}
		
		setVisible(true);
		
		
		
		
		
		
		
	}
	
	private class ButtonHandler implements ActionListener {

		
		public void actionPerformed(ActionEvent f) 
		{
			//Checks every spot on the board to see which button was pushed
			for (int i = 0; i< columns ; i++){
				for (int j = 0 ; j < rows ; j++){
					if(f.getSource() == board[i][j])
					{						
												
						if(surroundings[i][j]==0)
						{
							board[i][j].setVisible(false);
						}
						
						
					}
					
					
				}
				
			}
			
		}
		
	}
}
		
	










Is This A Good Question/Topic? 0
  • +

Replies To: Minesweeper assignment getSource()

#2 GregBrannon   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2250
  • View blog
  • Posts: 5,340
  • Joined: 10-September 10

Re: Minesweeper assignment getSource()

Posted 11 October 2011 - 10:09 PM

Post the error message exactly, cut and paste.
Was This Post Helpful? 0
  • +
  • -

#3 prosper   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 11-October 11

Re: Minesweeper assignment getSource()

Posted 11 October 2011 - 10:11 PM

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Project1Minesweeper$ButtonHandler.actionPerformed(Project1Minesweeper.java:200)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Was This Post Helpful? 0
  • +
  • -

#4 GregBrannon   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2250
  • View blog
  • Posts: 5,340
  • Joined: 10-September 10

Re: Minesweeper assignment getSource()

Posted 11 October 2011 - 10:45 PM

You haven't given the method getSource() a way to identify the button pushed. By default, getSource() will use the button's label (I think), but you didn't assign any labels to the buttons, so you're getting the null pointer. Absent labels, you can setActionCommand() to identify the buttons.
Was This Post Helpful? 1
  • +
  • -

#5 prosper   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 11-October 11

Re: Minesweeper assignment getSource()

Posted 11 October 2011 - 11:09 PM

Thanks for the quick reply. So I have to assign a unique id for each button? If I add the setActionCommand to the loop when making the buttons, should that fix it? Or how does it work exactly?
for (int i = 0; i< columns ; i++){
			for (int j = 0 ; j < rows ; j++){
				board[i][j] = new JButton(); 
				pane.add(board[i][j]);				
				board[i][j].addActionListener(Bhandler);
				board[i][j].setActionCommand(Integer.toString(i)+","+Integer.toString(j));
			}
			
		}


Was This Post Helpful? 0
  • +
  • -

#6 CasiOo   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1578
  • View blog
  • Posts: 3,551
  • Joined: 05-April 11

Re: Minesweeper assignment getSource()

Posted 12 October 2011 - 01:44 AM

You can make a new instance of your action listener class for every button, and then let the instance save the x, y position. Then the lookup in the array will be O(1)

//Initialize buttons
for (int y=0; y<buttons.length; y++) {
	for (int x=0; x<buttons.length; x++) {
		buttons[y][x] = new JButton();
		buttons[y][x].addActionListener( new ButtonListener(x, y) );
	}
}


private class ButtonListener implements ActionListener {
	private int x, y;
	
	public ButtonListener(int x, int y) {
		this.x = x;
		this.y = y;
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		System.out.println(x + ", " + y + " got clicked");
	}
}


Was This Post Helpful? 0
  • +
  • -

#7 prosper   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 11-October 11

Re: Minesweeper assignment getSource()

Posted 12 October 2011 - 02:29 AM

I think I'm supposed to use the getSource() as part of a requirement for this project. <_< I still haven't gotten it working though.
Was This Post Helpful? 0
  • +
  • -

#8 EPTRemain   User is offline

  • D.I.C Head

Reputation: 16
  • View blog
  • Posts: 81
  • Joined: 25-May 11

Re: Minesweeper assignment getSource()

Posted 12 October 2011 - 02:50 AM

View Postprosper, on 12 October 2011 - 11:29 AM, said:

I think I'm supposed to use the getSource() as part of a requirement for this project. <_< I still haven't gotten it working though.

private class ButtonListener implements ActionListener 
{
    public void actionPerformed(ActionEvent e) 
    {
        if (e.getSource() == yourButton) {
            //actions here
        } 
    }
}


Was This Post Helpful? 0
  • +
  • -

#9 prosper   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 11-October 11

Re: Minesweeper assignment getSource()

Posted 12 October 2011 - 02:53 AM

View PostEPTRemain, on 12 October 2011 - 02:50 AM, said:

View Postprosper, on 12 October 2011 - 11:29 AM, said:

I think I'm supposed to use the getSource() as part of a requirement for this project. <_< I still haven't gotten it working though.

private class ButtonListener implements ActionListener 
{
    public void actionPerformed(ActionEvent e) 
    {
        if (e.getSource() == yourButton) {
            //actions here
        } 
    }
}


That's what I had in the OP but I was getting the previously posted error.
Was This Post Helpful? 0
  • +
  • -

#10 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7507
  • View blog
  • Posts: 15,558
  • Joined: 16-October 07

Re: Minesweeper assignment getSource()

Posted 12 October 2011 - 04:45 AM

View Postprosper, on 12 October 2011 - 05:53 AM, said:

That's what I had in the OP but I was getting the previously posted error.


So you did.

Right, time for a little debug. I changed your code thus:
private class ButtonHandler implements ActionListener {
	public void actionPerformed(ActionEvent f) {
		Object source = f.getSource();
		System.out.println("source: " + source);
		System.out.println(columns);
		System.out.println(rows);
		
		for (int i = 0; i< columns ; i++) {
			for (int j = 0 ; j < rows ; j++){
				System.out.println(i + "," + j);
				System.out.println(board[i][j]);
				if(source == board[i][j]) {
					System.out.println("surroundings[i][j]==" + surroundings);
					if(surroundings[i][j]==0) { board[i][j].setVisible(false); }
				}
			}
		}
	}
}



Being able to see what's going on is often as simple as just printing it out. You can use cool IDE tools, but this trick always works.

And the output we got:
source: javax.swing.JButton...
10
10
0,0
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException



Looks like board[0][0] is missing something. I know you loaded it somewhere. Maybe you didn't load what you think you loaded?

Here it is:
public void GameStart() {
	// you are declaring a local variable called board
	JButton board [][] = new JButton[rows][columns];
	// from now on, all references to board will use this variable
	// ignoring the class level variable board



So:
public void GameStart() {
	board = new JButton[rows][columns];



Next error:
surroundings[i][j]==null
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException



Looks like you defined a lot of local references. Fix them and see how far you get.

On the design front, I'd avoid parallel arrays. Extend the JButton to contain row, column, surroundings, whatever else you need. Cast the getSource and use the magic values inside.


Hmmm... that could be vague. Here's an example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;

class BoardButton extends JButton {
	public boolean bomb;
	public int surroundings, row, col;
	BoardButton(int row, int col) { 
		super();
		this.row = row;
		this.col = col;
		surroundings = 0;
		bomb = false;
	}
}


public class Project1Minesweeper extends JFrame{

	private static int width = 800;
	private static int height = 800;
	private int bombsplaced = 0;
	Container pane;
	Container gamepane;
	private JLabel rowsL, columnsL, bombsL;
	private JTextField rowsTF, columnsTF, bombsTF;	
	private JButton startB, exitB;
	private StartButtonHandler startBhandler;
	private ExitButtonHandler exitBhandler;
	private ButtonHandler Bhandler;	
	BoardButton board [][];
	
	int rows , columns, bombs;
	
	public Project1Minesweeper()
	{
		setTitle("Minesweeper v.11 by Steven Wirth");
		setSize(width,height);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		pane = getContentPane();
		pane.setLayout(new GridLayout(4,2));
				
		rowsL = new JLabel("Enter the number of rows: ", SwingConstants.CENTER);
		columnsL = new JLabel("Enter the number of columns: ", SwingConstants.CENTER);
		bombsL = new JLabel("Enter the number of bombs: ", SwingConstants.CENTER);
		startB = new JButton("Start Game!");
		exitB = new JButton("Exit");
		
		rowsTF = new JTextField("10",10);
		columnsTF = new JTextField("10",10);
		bombsTF = new JTextField("10",10);
		
		pane.add(rowsL);
		pane.add(rowsTF);
		pane.add(columnsL);
		pane.add(columnsTF);
		pane.add(bombsL);				
		pane.add(bombsTF);
		pane.add(startB);
		pane.add(exitB);
		
		startBhandler = new StartButtonHandler();
		exitBhandler = new ExitButtonHandler();
		Bhandler = new ButtonHandler();
		startB.addActionListener(startBhandler);
		exitB.addActionListener(exitBhandler);
		
		setVisible(true);
		
	}
	public static void main(String[] args) {
		new Project1Minesweeper();

	}
	
	private class StartButtonHandler implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) 
		{
			GameStart();
			
		}
		
		
		
	}
	
	private class ExitButtonHandler implements ActionListener {
		public void actionPerformed(ActionEvent arg0)
		{
			System.exit(0);
		}

		
	}
	
	
	public void GameStart(){
		rows = Integer.parseInt(rowsTF.getText());
		columns = Integer.parseInt(columnsTF.getText());
		bombs = Integer.parseInt(bombsTF.getText());
		Random randomGenerator =new Random();
		
		
		board = new BoardButton[rows][columns];
		Boolean bomb [][] = new Boolean[rows][columns];
		int surroundings [][] = new int[rows][columns];
										
		setVisible(false);
		pane.removeAll();	
		
		setTitle("Minesweeper!!");
		setSize(800,800);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		pane.setLayout(new GridLayout(rows, columns));

		for (int i = 0; i< columns ; i++){
			for (int j = 0 ; j < rows ; j++){
				BoardButton b = new BoardButton(i,j); 
				pane.add(B)/>;				
				b.addActionListener(Bhandler);
				board[i][j] = b;
			}
		}

		while (bombsplaced<=bombs) {
			int RandomHeight = randomGenerator.nextInt(columns-1);
			int RandomWidth = randomGenerator.nextInt(rows-1);
			if (!board[RandomWidth][RandomHeight].bomb) {
				board[RandomWidth][RandomHeight].bomb = true;
				bombsplaced++;
			}
		}

		for (int i = 0; i< columns ; i++){
			for (int j = 0 ; j < rows ; j++){
				for(int x=(i-1); x<= (i + 1); x++) {
					for(int y=(j-1); y <=(j+1); y++) {
						if(x<0 || x>=columns || y<0 || y>=rows || !board[x][y].bomb) { break; }
						board[x][y].surroundings++;
					}
				}
			}
		}
		setVisible(true);
	}
	
	private class ButtonHandler implements ActionListener {
		public void actionPerformed(ActionEvent f) {
			BoardButton bb = (BoardButton)f.getSource();
			System.out.println("source: " + bb);
			if(bb.surroundings==0) {
				bb.setVisible(false);
			}
		}
	}
}



Hope this helps.

This post has been edited by baavgai: 12 October 2011 - 04:45 AM

Was This Post Helpful? 3
  • +
  • -

#11 prosper   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 11-October 11

Re: Minesweeper assignment getSource()

Posted 12 October 2011 - 07:19 AM

Thanks! This really helped a lot! Now I have to figure out how to clear all adjacent squares when a square without a bomb is selected. As for the parallel arrays, thanks for the input and I'll definitely look into that, but I don't think I'm good enough at programming to switch over to that right now. I would try it for this project but it's due tomorrow.
Was This Post Helpful? 0
  • +
  • -

#12 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7507
  • View blog
  • Posts: 15,558
  • Joined: 16-October 07

Re: Minesweeper assignment getSource()

Posted 12 October 2011 - 07:44 AM

Clearing is most easily done with recursion. The trick is not going over the same place twice.

Your first selection is special, you check for bomb, no bomb. Then you check all surrounding cells for zero surrounding cells. If that cell is a zero, you reveal it and then check all the cells surrounding that.
Was This Post Helpful? 1
  • +
  • -

#13 prosper   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 11-October 11

Re: Minesweeper assignment getSource()

Posted 13 October 2011 - 12:35 AM

View Postbaavgai, on 12 October 2011 - 07:44 AM, said:

Clearing is most easily done with recursion. The trick is not going over the same place twice.

Your first selection is special, you check for bomb, no bomb. Then you check all surrounding cells for zero surrounding cells. If that cell is a zero, you reveal it and then check all the cells surrounding that.

Alright, so I think I fixed most the local variable issues and I think I took care of the recursion method. Upon testing I found that for some reason the first column is for some reason being skipped by my loop that assigns integers for surrounding bombs so they are all being left as the default value (0) and clear when they are clicked on. Bombs do spawn in the first column however, since the integer value is 0 it gets cleared, I can only tell that a bomb is there by the values in the next column. Anyway, here is the code that I think is at fault for this:
for (int i = 0; i< columns ; i++){
			for (int j = 0 ; j < rows ; j++){
				for(int x=(i-1); x<= (i + 1); x++)
				{
					for(int y=(j-1); y <=(j+1); y++)
					{
						
						
						//Stops the adjacent squares from clearing if the entry is out of bounds
						if(x<0 || x>=columns || y<0 || y>=rows)
						{
							break;
						}
						
						else if (bomb[x][y]==true)
						{
							surroundings[i][j]++;
							break;
						}
						
						
				}
			}
			}
		}



I looked at it and tried writing out all the values of things but I can't find anything wrong with it, I have been up for quite some time though. I'm also posting all the modified code for the entire program just in case I'm completely wrong with where the error is or if anyone wanted to see what I changed and the recursion I added. Thanks again for all the help!
import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
import java.util.Random;

public class Project1Minesweeper extends JFrame{

	private static int width = 800;
	private static int height = 800;
	private int bombsplaced = 0;
	Container pane;
	Container gamepane;
	private JLabel rowsL, columnsL, bombsL;
	private JTextField rowsTF, columnsTF, bombsTF;	
	private JButton startB, exitB;
	private StartButtonHandler startBhandler;
	private ExitButtonHandler exitBhandler;
	private ButtonHandler Bhandler;	
	JButton board [][];
	Boolean bomb [][];
	int surroundings [][];
	
	int rows , columns, bombs;
	
	public Project1Minesweeper()
	{
		setTitle("Minesweeper v.11 by Steven Wirth");
		setSize(width,height);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		pane = getContentPane();
		pane.setLayout(new GridLayout(4,2));
				
		rowsL = new JLabel("Enter the number of rows: ", SwingConstants.CENTER);
		columnsL = new JLabel("Enter the number of columns: ", SwingConstants.CENTER);
		bombsL = new JLabel("Enter the number of bombs: ", SwingConstants.CENTER);
		startB = new JButton("Start Game!");
		exitB = new JButton("Exit");
		
		rowsTF = new JTextField("10",10);
		columnsTF = new JTextField("10",10);
		bombsTF = new JTextField("10",10);
		
		pane.add(rowsL);
		pane.add(rowsTF);
		pane.add(columnsL);
		pane.add(columnsTF);
		pane.add(bombsL);				
		pane.add(bombsTF);
		pane.add(startB);
		pane.add(exitB);
		
		startBhandler = new StartButtonHandler();
		exitBhandler = new ExitButtonHandler();
		Bhandler = new ButtonHandler();
		startB.addActionListener(startBhandler);
		exitB.addActionListener(exitBhandler);
		
		setVisible(true);
		
	}
	public static void main(String[] args) {
		new Project1Minesweeper();

	}
	
	private class StartButtonHandler implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) 
		{
			GameStart();
			
		}
		
		
		
	}
	
	private class ExitButtonHandler implements ActionListener {
		public void actionPerformed(ActionEvent arg0)
		{
			System.exit(0);
		}

		
	}
	
	
	
	public void GameStart()
	{
		
		
		
		rows = Integer.parseInt(rowsTF.getText());
		columns = Integer.parseInt(columnsTF.getText());
		bombs = Integer.parseInt(bombsTF.getText());
		Random randomGenerator =new Random();
		
		
		board = new JButton[rows][columns];
		bomb = new Boolean[rows][columns];
		surroundings  = new int[rows][columns];
										
		setVisible(false);
		pane.removeAll();	
		
		setTitle("Minesweeper!!");
		setSize(800,800);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		pane.setLayout(new GridLayout(rows, columns));

		
//Draws all the buttons on the board		
		for (int i = 0; i< columns ; i++){
			for (int j = 0 ; j < rows ; j++){
				board[i][j] = new JButton(); 
				board[i][j].setActionCommand(Integer.toString(i)+","+Integer.toString(j));
				pane.add(board[i][j]);				
				board[i][j].addActionListener(Bhandler);
				
			}
			
		}
		
//Makes all the spaces on the board "false" for bombs		
		for (int i = 0; i< columns ; i++){
			for (int j = 0 ; j < rows ; j++){
				bomb[i][j] = false; 
				
			}
			
		}
//Makes the value of all the spaces in the surroundings array 0
		for (int i = 0; i< columns ; i++){
			for (int j = 0 ; j < rows ; j++){
				surroundings[i][j] = 0; 
				
			}
			
		}
		
//Adds bombs to the board in random spaces
		while (bombsplaced<bombs)
		{
			int RandomHeight = randomGenerator.nextInt(columns-1);
			int RandomWidth = randomGenerator.nextInt(rows-1);
			
			if (bomb[RandomWidth][RandomHeight] == false)
			{
				bomb[RandomWidth][RandomHeight] = true;
				bombsplaced++;
			}
			
			
		}

//Checks the eight squares around each button and assigns that number to that square so that it can be checked later		
		for (int i = 0; i< columns ; i++){
			for (int j = 0 ; j < rows ; j++){
				for(int x=(i-1); x<= (i + 1); x++)
				{
					for(int y=(j-1); y <=(j+1); y++)
					{
						
						
						//Stops the adjacent squares from clearing if the entry is out of bounds
						if(x<0 || x>=columns || y<0 || y>=rows)
						{
							break;
						}
						
						else if (bomb[x][y]==true)
						{
							surroundings[i][j]++;
							break;
						}
						
						
				}
			}
			}
		}
		
		setVisible(true);
		
		
		
		
		
		
		
	}
	
	private class ButtonHandler implements ActionListener {

		
		public void actionPerformed(ActionEvent f) 
		{
			//Checks every spot on the board to see which button was pushed
			for (int i = 0; i< columns ; i++){
				for (int j = 0 ; j < rows ; j++){
					if(f.getSource() == board[i][j])
					{						
												
						if(surroundings[i][j]==0)
						{
							board[i][j].setVisible(false);
							Clear(i,j);
						}
						
						if(surroundings[i][j]>0)
						{
							board[i][j].setLabel(Integer.toString(surroundings[i][j]));
						}
						if(bomb[i][j]==true)
						{
							board[i][j].setLabel("Bomb");
						}
					}
					
					
				}
				
			}
			
		}
	}
		private void Clear(int i, int j) {
			
					for(int x=(i-1); x<= (i + 1); x++)
					{
						for(int y=(j-1); y <=(j+1); y++)
						{
							while(true){
							
							
							if(x<0 || x>=columns || y<0 || y>=rows)
							{
								break;
							}
							
							else if (surroundings[x][y]==0)
							{
								board[x][y].setVisible(false);
								Clear(x,y);
								break;
							}
							
							else
							{
								break;
							}
					
				}
				}
			}
			
			
		}

		
		
		
	}

		
	



Was This Post Helpful? 0
  • +
  • -

#14 prosper   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 11-October 11

Re: Minesweeper assignment getSource()

Posted 13 October 2011 - 01:00 AM

Grrr....Just noticed in my recursion method that if it hits a 0 in the middle of checking all 8 squares around the initial one, it stops checking them all. Hmm.....
Was This Post Helpful? 0
  • +
  • -

#15 CasiOo   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1578
  • View blog
  • Posts: 3,551
  • Joined: 05-April 11

Re: Minesweeper assignment getSource()

Posted 13 October 2011 - 01:14 AM

I have no idea why you are having the while(true) loop.

I would have written it like
  public void clear( int x, int y ) {
    myArray[x][y] = 1;
    
    for ( int i = x - 1; i <= x + 1; i++ ) {
      for ( int k = y - 1; k <= y + 1; k++ ) {
        if (isOutOfBounds( i, k ) || (i == x && k == y)) //Continue loop if true
          continue;
        
        if (myArray[i][k] == 0) {
          System.out.println(i + ", " + k);
          clear( i, k );
        }
      }
    }
  }



Edit: it wasn't correct and made a typo

This post has been edited by CasiOo: 13 October 2011 - 01:30 AM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2