// FlipFlop.java // Raja Sooriamurthi // // An applet using the JDK 1.1 event model // to play the game of "Lights Out" // // 1999/11/03 Initial version /* */ import java.applet.*; import java.awt.*; import java.awt.event.*; public class FlipFlop extends Applet { int gameSize = 6; int numButtons = gameSize*gameSize; int buttonSize = 65; private boolean[] state; private Button[] buttons; public void init() { // all initialized to false state = new boolean[numButtons]; buttons = new Button[numButtons]; setLayout (new BorderLayout()); Panel p0 = new Panel(); p0.setLayout(new FlowLayout(FlowLayout.CENTER)); Button startButton = new Button("Start"); startButton.setBackground(Color.blue); startButton.setForeground(Color.yellow); startButton.addActionListener (new StartButtonL()); p0.add(startButton); // *** "North" is case sensitive !! add("North", p0); Panel p1 = new Panel(); p1.setLayout(new GridLayout(gameSize, gameSize)); for (int i = 0; i < numButtons; i++) { buttons[i] = new Button(Integer.toString(i)); buttons[i].setSize (buttonSize, buttonSize); buttons[i].addActionListener (new ButtonL()); p1.add(buttons[i]); show(i); } // *** "Center" is case sensitive !! add("Center", p1); setSize (gameSize*buttonSize, gameSize*buttonSize + p0.getSize().height); setBackground (Color.cyan); repaint(); } // ********************************* // A listener for the "start" button // ********************************* class StartButtonL implements ActionListener { public void actionPerformed (ActionEvent e) { for (int i=0; i 0.5) click(i); } } // **************************** // Listners for each button // **************************** class ButtonL implements ActionListener { public void actionPerformed (ActionEvent e) { int i = Integer.parseInt (e.getActionCommand()); click (i); } } // ************************* // Click // ************************* // Click toggles button i as well as each of its // neighbors on its four sides -if- they exist private void click (int i) { // toggle the clicked button System.out.println ("Clicked " + i); toggle(i); // toggle the left if (i%gameSize != 0) toggle(i-1); // toggle the right if (i%gameSize < gameSize-1) toggle(i+1); // toggle the below if (i >= gameSize) toggle(i-gameSize); // toggle the above if (i < numButtons-gameSize) toggle(i+gameSize); repaint(); } // ************************* // toggle // ************************* private void toggle (int i) { state[i] = !state[i]; show (i); } // ************************* // show // ************************* private void show (int i) { buttons[i].setBackground (state[i] ? Color.red: Color.green); } }