CS 201 - Computer Science I - Spring 2003
Examples


Loyola College > Department of Computer Science > CS 201 > Examples > 15 Puzzle

source code

import java.awt.*;
import java.applet.*;

/**
 * Constructs the interface for a 15-puzzle.
 *
 * @author Jim Glenn
 * @version 0.1 3/17/2003
 */

public class FifteenPuzzle extends Applet
{
	/**
	 * Initializes the user interface for this applet.
	 */

	public void init()
	{
		// the applet has a 1x2 BorderLayout with the puzzle
		// on the left and the controls on the right

		this.setLayout(new GridLayout(1, 2));

		// the tiles in the puzzle go in a 4x4 grid
		
		Panel puzzlePanel;
		puzzlePanel = new Panel(new GridLayout(4, 4));
		
		// make TextFields for the tiles; this will be
		// ugly as written
		
		puzzlePanel.add(new TextField("1"));
		puzzlePanel.add(new TextField("2"));
		puzzlePanel.add(new TextField("3"));
		puzzlePanel.add(new TextField("4"));
		puzzlePanel.add(new TextField("5"));
		puzzlePanel.add(new TextField("6"));
		puzzlePanel.add(new TextField("7"));
		puzzlePanel.add(new TextField("8"));
		puzzlePanel.add(new TextField("9"));
		puzzlePanel.add(new TextField("10"));
		puzzlePanel.add(new TextField("11"));
		puzzlePanel.add(new TextField("12"));
		puzzlePanel.add(new TextField("13"));
		puzzlePanel.add(new TextField("14"));
		puzzlePanel.add(new TextField("15"));
		
		// the controls go in a 4x1 grid with the direction
		// buttons in the top cell, the color Checkboxes
		// in the next cell, then the sound control and
		// finally the reshuffle button
		
		Panel controlPanel;
		controlPanel = new Panel(new GridLayout(4, 1));
		
		// to get four components in one cell, we need
		// to grup them into a panel
		
		Panel movePanel;
		movePanel = new Panel(new BorderLayout());
		movePanel.add(new Button("UP"), BorderLayout.NORTH);
		movePanel.add(new Button("DOWN"), BorderLayout.SOUTH);
		movePanel.add(new Button("LEFT"), BorderLayout.WEST);
		movePanel.add(new Button("RIGHT"), BorderLayout.EAST);
		
		// the three color controls go in another panel
		
		Panel colorPanel;
		colorPanel = new Panel();
		
		// the checkbox makes sure that only one color is
		// selected at a time
		
		CheckboxGroup colorGroup;
		colorGroup = new CheckboxGroup();
		Checkbox redBox;
		redBox = new Checkbox("Red", true, colorGroup);
		Checkbox whiteBox;
		whiteBox = new Checkbox("White", false, colorGroup);
		Checkbox purpleBox;
		purpleBox = new Checkbox("Purple", false, colorGroup);
		colorPanel.add(redBox);
		colorPanel.add(whiteBox);
		colorPanel.add(purpleBox);
		
		// add the four parts of the control panel
		
		controlPanel.add(movePanel);
		controlPanel.add(colorPanel);
		controlPanel.add(new Checkbox("Sound"));
		controlPanel.add(new Button("Reshuffle"));
		
		// add the puzzle and the controls to the applet
		
		this.add(puzzlePanel);
		this.add(controlPanel);
	}
}