Ecco un esempio:
codice:
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class SameGameFrame extends JFrame
{
private SameGameBoard board;
public SameGameFrame ()
{
super ("Same Game");
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
board = new SameGameBoard (5, 10, 32);
board.initRandom ();
Container contentPane = getContentPane ();
contentPane.add (board);
pack ();
}
public static void main (String[] args)
{
SwingUtilities.invokeLater (new Runnable ()
{
public void run ()
{
SameGameFrame f = new SameGameFrame ();
f.setVisible (true);
}
});
}
}
class SameGameBoard extends JPanel
{
public static final byte EMPTY = 0;
public static final byte RED = 1;
public static final byte GREEN = 2;
public static final byte BLUE = 3;
private int rows;
private int columns;
private int cellSize;
private byte[][] board;
private Dimension dim;
public SameGameBoard (int rows, int columns, int cellSize)
{
this.rows = rows;
this.columns = columns;
this.cellSize = cellSize;
board = new byte[rows][columns];
dim = new Dimension (columns * cellSize, rows * cellSize);
}
public void initRandom ()
{
Random rnd = new Random ();
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < columns; c++)
{
board[r][c] = (byte) (rnd.nextInt (3) + 1);
}
}
repaint ();
}
public Dimension getPreferredSize ()
{
return dim;
}
protected void paintComponent (Graphics g)
{
super.paintComponent (g);
Color oldColor = g.getColor ();
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < columns; c++)
{
int y = r * cellSize;
int x = c * cellSize;
g.setColor (Color.WHITE);
g.fillRect (x, y, cellSize, cellSize);
switch (board[r][c])
{
case RED:
g.setColor (Color.RED);
g.fillOval (x, y, cellSize, cellSize);
break;
case GREEN:
g.setColor (Color.GREEN);
g.fillOval (x, y, cellSize, cellSize);
break;
case BLUE:
g.setColor (Color.BLUE);
g.fillOval (x, y, cellSize, cellSize);
break;
}
}
}
g.setColor (oldColor);
}
}
L'ho scritto velocemente quindi non è certo il massimo della efficienza/bellezza. Ma è davvero molto semplice e lineare. Come puoi vedere non sono cose difficili da fare. Basta solo sfruttare ciò che Java mette a disposizione. Quindi basta usare "bene" array, cicli e un pizzico di matematica basilare.