// FlipFlop_soln.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_soln extends Applet
{
int gameSize = 5;
int numButtons = gameSize*gameSize;
int buttonSize = 65;
Color ON_COLOR = Color.red;
Color OFF_COLOR = Color.green;
Color SOLN_COLOR = Color.pink;
private boolean[] state;
// state will point to either one of the below
// depending on the mode
private boolean[] playState, solveState;
private Button[] buttons;
private void playMode()
{
state = playState;
}
private boolean isPlayMode()
{
return( state == playState );
}
private void solveMode()
{
// copy the current play state
for( int i=0; i 0.5 ) click( i );
}
}
}
// *********************************
// A listener for the "solve" button
// *********************************
class SolveButtonL implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
solve();
}
}
// ****************************
// Listeners 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];
if( isPlayMode() ) updateButton( i );
}
// *************************
// updateButton
// *************************
private void updateButton( int i )
{
buttons[i].setBackground( state[i] ? ON_COLOR : OFF_COLOR );
}
// *************************
// solve
// *************************
private void solve()
{
int limit = (int) Math.pow( 2, gameSize );
for( int i = 0; i 0 )
{
if( n%2 == 1 )
{
buttons[i].setBackground( SOLN_COLOR );
}
n = n/2;
i-- ;
}
}
// ******************************
// clickFirstRow
// ******************************
private void clickFirstRow( int n )
{
int i = gameSize-1;
while( n > 0 )
{
if( n%2 == 1 )
{
click( i );
}
n = n/2;
i-- ;
}
}
// ******************************
// gameSolved
// ******************************
private boolean gameSolved()
{
for( int i=0; i