/* */ import java.applet.*; import java.awt.*; import java.awt.event.*; public class Flip extends Applet { static final int size = 6; static final int cellSize = 65; boolean[] state; Component[] indicators; public void init() { setLayout (new BorderLayout()); state = new boolean[size*size]; Panel controlPanel = new Panel(); controlPanel.setLayout(new FlowLayout(FlowLayout.CENTER)); controlPanel.add(new Button("Randomize")); add("North", controlPanel); Panel mainPanel = new Panel(); mainPanel.setLayout(new GridLayout(size, size)); for (int i = 0; i < size*size; i++) mainPanel.add(new Button("" + i)); add("Center", mainPanel); } /** The flip method takes care of flipping one of the "keys" on the * board -- such as the one clicked-on or one of its neighbors. This * procedure is responsible both for updating the object's record of which * state the key is in and also for actually recoloring the displayed key * (using the recolor method). */ protected void flip(int key) { state[key] = !state[key]; recolor(key); } /** The recolor method updates the displayed color of one of the keys * on the board to reflect the current flippedness state of that key. */ protected void recolor(int n) { indicators[n].setBackground(state[n] ? Color.red : Color.green); } /** The randomize method independently chooses whether to flip each key * with a 50/50 chance for each. Note that for some board sizes this * kind of randomization might lead to board configurations that can * not be solved (to a single-color state) by any combination of * mouse clicks. If such sizes are to be used, it would be better to * have the randomize procedure act like the user interface does, flipping * a key and its neighbors rather than just the one key. */ protected void randomize() { for(int i = 0; i < size*size; i++){ if(Math.random() > .5){ flip(i); } } } public static void main(String[] args) { new Flip(); } }