More Minesweeper
starting point
class MineSweeper extends JPanel implements ActionListener, MouseListener
{
// (Object Oriented stuff for MineSweeper object goes here)
protected JPanel mfPanel;
protected MSButton[][] buttons;
public void init(int Rows, int Cols, int numMines)
{
buttons = new MSButton[Rows][Cols];
this.setLayout(new BorderLayout);
mfPanel = new JPanel();
mfPanel.setLayout(new GridLayout(Rows, Cols, 4,4));
for (int r = 0; r < Rows; r++) {
for (int c = 0; c < Cols, c++) {
// initialize a button, mouse, and action listener. add to panel.
buttons[r][c] = new MSButton(r,c);
buttons[r][c].addActionListener(this);
buttons[r][c].addMouseListener(this);
mfPanel.add(buttons[r][c]);
}
}
this.add(mfPanel, BorderLayout.CENTER);
int nMines = 0;
while (nMines < numMines) { // load in mines, make sure there aren't duplicates
r = Math.rand(Rows);
c = Math.rand(Cols);
if (buttons[r][c].value != '*') {
buttons[r][c].value = '*';
nMines++;
} // end if
} // end while
// just setting up the minefield
for (r=0, r<Rows, r++) {
for (c=0; c<Cols, c++) {
if (buttons[r][c] == '*') continue;
int count = 0;
for (int j = r-1; j <= r+1; j++) {
for (i=c-1; i<=c+1; i++) {
if (j < 0 || j >= buttons.length || i < 0 || i >= buttons[j].length) continue; // array out of bounds check
if (buttons[r][c].value == '*') count++;
else
buttons[r][c].value = ' ';
}
}
if (count > 0) buttons[r][c].value = count + '0';
}
} // end ALL the loops
}
public MineSweeper()
{
initGui(rows,columns);
resetGame(rows,columns);
}
idea for the main method:
public static void main(String[] args)
{
JFrame f = new JFrame("MineSweep2k12");
MineSweeper ms = new MineSweeper();
f.setSize(500,500);
f.getContentPane().add(f, BorderLayout.CENTER);
f.setVisible(true);
}
}
class MSButton extends JButton
{
char val;
boolean isCovered;
int r, c;
}
Another method in MineSweeper class:
public void mouseClicked( MouseEvent e)
{
// (insert code to check that the source of the event is indeed a MSButton)
MSButton b = (MSButton) e.getSource();
if (e.getButton() == 1) { // check documentation for sure, 1= left maybe
// do left click logic
uncover(b.r,b.c);
}
else {
// do right click logic
// basically, if covered, put a flag.
}