The Towers of Hanoi Java program is a visual representation of a classic puzzle known as the “Tower of Hanoi.” The puzzle involves three pegs and a set of disks of different sizes. The goal is to move the entire stack of disks from one peg to another, following specific rules:
This Java Program solves the Towers of Hanoi problem for a tower of 10 disks. Ten differently-sized disks are stacked in a pile, in order of decreasing size. There are two other places for piles. The object is to move the pile to the second available place, subject to the rules that only one disk at a time can be moved, and no disk can be piled on top of a smaller disk. The solution is shown as an animation. The Towers of Hanoi problem is a standard example of recursion.
The main functionalities of the Towers of Hanoi program are:
- Hanoi Tower Animation: The program visualizes the Towers of Hanoi problem, displaying the three towers and a set of disks initially stacked in decreasing order of size on one of the towers.
- Recursive Solution: The program solves the Towers of Hanoi problem using recursion. The recursive algorithm moves the disks from one tower to another following the rules of the puzzle. It demonstrates the recursive nature of the problem-solving technique.
- Animation of Disk Movement: The movement of disks is animated, providing a visual representation of how the recursive algorithm works. Disks are displayed in different colors, and the program animates the process of moving a disk from one tower to another.
- User Interface (UI): The program uses Java’s Swing library to create a graphical user interface for the applet. It includes the main frame and draws the towers and disks within that frame. The UI is updated during the animation to reflect the current state of the Towers of Hanoi puzzle.
- Applet Lifecycle Management: The program utilizes the applet lifecycle methods (
init()
,start()
,stop()
,destroy()
) for proper initialization, starting, stopping, and destruction of the applet. Additionally, themain
method is provided to run the applet as a standalone application. - Threading and Animation Timer: The program uses a
java.lang.Thread
to control the animation and manage the timing of disk movements. It ensures a smooth and controlled visual representation of the Towers of Hanoi solution. - Off-Screen Canvas (OSC): The program creates an off-screen canvas to improve graphics rendering efficiency. The off-screen canvas is used to draw the current frame, which is then displayed on the screen.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | import java.awt.*; import javax.swing.JApplet; import javax.swing.JFrame; import javax.swing.SwingUtilities; public class TowersOfHanoi extends JApplet implements Runnable { private static Color BACKGROUND_COLOR = new Color(255,255,180); private static Color BORDER_COLOR = new Color(100,0,0); private static Color DISK_COLOR = new Color(0,0,180); private static Color MOVE_DISK_COLOR = new Color(180,180,255); private Image OSC; // The off-screen canvas. private static final int GO = 1, SUSPEND = 2, TERMINATE = 3; // Values for status. private int status = GO; // Controls the execution of the thread. private Thread runner; // A thread to run the animation. /* The following variables are the data needed for the animation. The three "piles" of disks are represented by the variables tower and towerHeight. towerHeight[i] is the number of disks on pile number i. For i=0,1,2 and for j=0,1,...,towerHeight[i]-1, tower[i][j] is an integer representing one of the ten disks. (The disks are numbered from 1 to 10.) (tower is null between repetitions of the solution.) During the solution, as one disk is moved from one pile to another, the variable moveDisk is the number of the disk that is being moved, and moveTower is the number of the pile that it is currently on. This disk is not stored in the tower variable. it is drawn in a different color from the other disks. All the data in these variables is for use in the drawCurrentFrame() method, which redraws the whose picture for each frame of the animation. */ private int[][] tower; private int[] towerHeight; private int moveDisk; private int moveTower; public void init() { setBackground(BACKGROUND_COLOR); } public void run() { // Run the animated solution over and over until the status // variable is set to TERMINATED. When this happens, the // delay() method will throw an IllegalArgumentException // and the run() method will be terminated. try { while (true) { tower = null; if (OSC != null) { Graphics g = OSC.getGraphics(); drawCurrentFrame(g); g.dispose(); } repaint(); delay(1000); synchronized(this) { tower = new int[3][10]; for (int i = 0; i < 10; i++) tower[0][i] = 10 - i; towerHeight = new int[3]; towerHeight[0] = 10; if (OSC != null) { Graphics g = OSC.getGraphics(); drawCurrentFrame(g); g.dispose(); } repaint(); delay(1000); } solve(10,0,1,2); delay(2000); } } catch (IllegalArgumentException e) { } } private void solve(int disks, int from, int to, int spare) { // Solve the problem of moving the number of disks specified // by the first parameter from the pile specified by the // second parameter to the pile specified by the third parameter. // The pile specified by the fourth parameter is available // for use as a spare. On the "top level", this recursive // subroutine is called by the run() method. if (disks == 1) moveOne(from,to); else { solve(disks-1, from, spare, to); moveOne(from,to); solve(disks-1, spare, to, from); } } synchronized private void moveOne(int fromStack, int toStack) { // Move the disk at the top of pile number fromStack to // the top of pile number toStack. (The disk changes to // a new color, then moves, then changes back to the standard // color. moveDisk = tower[fromStack][towerHeight[fromStack]-1]; moveTower = fromStack; delay(120); towerHeight[fromStack]--; putDisk(MOVE_DISK_COLOR,moveDisk,moveTower); delay(80); putDisk(BACKGROUND_COLOR,moveDisk,moveTower); delay(80); moveTower = toStack; putDisk(MOVE_DISK_COLOR,moveDisk,moveTower); delay(80); putDisk(DISK_COLOR,moveDisk,moveTower); tower[toStack][towerHeight[toStack]] = moveDisk; towerHeight[toStack]++; moveDisk = 0; } private void putDisk(Color color, int disk, int t) { // Draw the specified disk on top of the pile number t. // This disk is NOT part of the data for the tower that // is stored in the tower[][] array. This routine is // only called by moveOne. (But if OSC is null, then // the call to repaint() will redraw the entire frame on // the screen.) if (OSC != null) { Graphics g = OSC.getGraphics(); g.setColor(color); g.fillRoundRect(75+140*t - 5*disk - 5, 116-12*towerHeight[t], 10*disk+10, 10, 10, 10); g.dispose(); } repaint(); } synchronized void drawCurrentFrame(Graphics g) { // Called to draw the current frame. But it is not drawn during // the animation of the solution. During the animation, the // moveDisk() method just modifies the existing picture. g.setColor(BACKGROUND_COLOR); g.fillRect(0,0,430,143); g.setColor(BORDER_COLOR); g.drawRect(0,0,429,142); g.drawRect(1,1,427,140); if (tower == null) return; g.fillRect(10,128,130,5); g.fillRect(150,128,130,5); g.fillRect(290,128,130,5); g.setColor(DISK_COLOR); for (int t = 0; t < 3; t++) { for (int i = 0; i < towerHeight[t]; i++) { int disk = tower[t][i]; g.fillRoundRect(75+140*t - 5*disk - 5, 116-12*i, 10*disk+10, 10, 10, 10); } } if (moveDisk > 0) { g.setColor(MOVE_DISK_COLOR); g.fillRoundRect(75+140*moveTower - 5*moveDisk - 5, 116-12*towerHeight[moveTower], 10*moveDisk+10, 10, 10, 10); } } synchronized void delay(int milliseconds) { // This routine is called repeatedly during the animation, // between frames. It delays for the specified number // of milliseconds. It handles suspension of the // program by not returning as long as the status variable // has the value SUSPEND. And it handles termination of // the program by throwing an IllegalArgumentException if // the status variable is TERMINATE. This exception will // be caught in the run() method, which will terminate // in response. if (status == TERMINATE) throw new IllegalArgumentException("Terminated"); try { wait(milliseconds); } catch (InterruptedException e) { } while (status == SUSPEND) { try { wait(); } catch (InterruptedException e) { } } if (status == TERMINATE) throw new IllegalArgumentException("Terminated"); } synchronized public void start() { // When program is started or restarted, start or // restart the thread. status = GO; // Indicates that the applet is running. if (runner == null || !runner.isAlive()) { tower = null; runner = new Thread(this); runner.start(); } else { notify(); } } synchronized public void stop() { // When the program is stopped, change the status // to SUSPEND. status = SUSPEND; notify(); } synchronized public void destroy() { // When the program is killed, change the status // to TERMINATE. status = TERMINATE; notify(); } synchronized public void paint(Graphics g) { // Paint the program by copying the OSC to the // screen. (If the OSC could not be created, // draw the current frame directly.) if (OSC == null) setupOSC(); if (OSC == null) drawCurrentFrame(g); else g.drawImage(OSC,0,0,this); } public void update(Graphics g) { // Modified so the program doesn't get cleared before it is painted. paint(g); } synchronized private void setupOSC() { OSC = null; // Free memory currently used by OSC. try { OSC = createImage(430,143); } catch (OutOfMemoryError e) { OSC = null; return; } Graphics OSG = OSC.getGraphics(); drawCurrentFrame(OSG); OSG.dispose(); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("Towers of Hanoi"); TowersOfHanoi applet = new TowersOfHanoi(); frame.add(applet); frame.setSize(430, 143); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); applet.init(); applet.start(); }); } } |