// This file contains excerpts from the textbook Concrete // Abstractions: An Introduction to Computer Science Using Scheme, by // Max Hailperin, Barbara Kaiser, and Karl Knight, Copyright (c) 1998 // by the authors. Full text is available for free at // http://www.gustavus.edu/+max/concrete-abstractions.html import java.awt.*; public class Puzzle extends java.applet.Applet { private int size = 4; // how many buttons wide and high private Button[][] buttons; private int blankRow, blankCol; // position of the blank space public void init(){ setLayout(new BorderLayout()); Panel controlPanel = new Panel(); add(controlPanel, "North"); Panel mainPanel = new Panel(); add(mainPanel, "Center"); Button initializeButton = new Button("Initialize"); initializeButton.addActionListener (new InitializeActionListener(this)); controlPanel.add(initializeButton); mainPanel.setLayout(new GridLayout(size, size)); buttons = new Button[size][size]; for(int row = 0; row < size; row++){ for(int col = 0; col < size; col++){ Button b = new Button(); buttons[row][col] = b; b.addActionListener(new TileActionListener (this, row, col)); mainPanel.add(b); } } initializeTiles(); } public void initializeTiles(){ int buttonCount = 0; for(int row = 0; row < size; row++){ for(int col = 0; col < size; col++){ buttonCount++; buttons[row][col].setLabel("" + buttonCount); } } blankRow = size - 1; blankCol = size - 1; buttons[blankRow][blankCol].setLabel(""); } public void pushTile(int row, int col){ if(row == blankRow){ for( ; blankCol < col; blankCol++){ buttons[blankRow][blankCol].setLabel (buttons[blankRow][blankCol+1].getLabel()); } for( ; blankCol > col; blankCol--){ buttons[blankRow][blankCol].setLabel (buttons[blankRow][blankCol-1].getLabel()); } } else if(col == blankCol){ for( ; blankRow < row; blankRow++){ buttons[blankRow][blankCol].setLabel (buttons[blankRow+1][blankCol].getLabel()); } for( ; blankRow > row; blankRow--){ buttons[blankRow][blankCol].setLabel (buttons[blankRow-1][blankCol].getLabel()); } } buttons[blankRow][blankCol].setLabel(""); } public void pushRandomTile(){ int row = (int) (Math.random() * size); int col = (int) (Math.random() * size); pushTile(row, col); } public void randomizeTiles(){ for(int i = 0; i < 100; i++){ pushRandomTile(); } } }