# Randomizing cells in a grid

• December 18th, 2010, 08:49 PM
Flowbs
Randomizing cells in a grid
Hello all, happy holidays!

I am here to seek some assistance in solving a homework problem. I know the code will not be written for me, I am just looking for a guiding hand. What my problem involves is designing a java applet that resembles minesweeper. I have made a 10x10 grid for the playing field. What I need to do is randomize the cells so that twenty of them are "mines" and the rest are "duds". I'm feeling very lost at the moment and any tips that would send me in the right direction would be great.

Thanks
Flowbs
• December 18th, 2010, 09:42 PM
helloworld922
Re: Randomizing cells in a grid
A simple method is to create a 10*10 array of booleans to false (being devoid of mines). Then you just need to pick 20 random (x,y) integer pairs (use the Random class or Math.random) and set those to spots to contain a mine by setting that coordinate to true. Make sure to check to see if that spot already contains a mine, otherwise you'll end up with a game map with possibly less than 20 mines (and the chances of this happening are quite high).

A second alternative is to create a set of the coordinates which contains mines (see the HashSet Javadoc).
• December 18th, 2010, 09:43 PM
copeg
Re: Randomizing cells in a grid
The Random class provides the capability for pseudo-random values. Can be used to randomize in a grid by getting 2 random values between 1 and 10 (or 0 and 9 for an array) to randomize a piece.
• December 18th, 2010, 09:53 PM
Flowbs
Re: Randomizing cells in a grid
Thanks, guys. Also, I'm having a bit of a problem trying to set out my initial layout again. I had the 10x10 grid set up, but I also needed to add three labels/buttons on top of the grid, and it's throwing me off a little bit.

Code Java:

```import java.awt.*; import javax.swing.*; import java.awt.event.*;   public class Ex3_1 extends JApplet { int numButtons; String s; private JButton b = new JButton("start over"); private JLabel l1 = new JLabel("attempts: "); private JLabel l2 = new JLabel("found: "); private JPanel p1, p2; private GridLayout grid1; private Container pane;   public void init() { Container pane = getContentPane(); pane.setLayout(new GridLayout(1, 1, 0, 5));   JPanel top = new JPanel(); top.setLayout(new FlowLayout()); top.add(l1); top.add(l2); top.add(b);   JPanel bottom = new JPanel(); bottom.setLayout(new FlowLayout()); s = getParameter("NUMBUTTONS"); numButtons = Integer.valueOf(s).intValue(); grid1 = new GridLayout(10, 10); for (int i=1; i<=numButtons; i++ ) bottom.add(new Button("") );       pane.add(top); pane.add(bottom); } }```

With this code, I have the three buttons on the left and a distorted grid on the right side of the panel. I think trying to put the grid on a panel is throwing it all off, am I going about this all wrong?