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
|
/*Alexander Pickering
*Data Structures Mon. Wed. @ 09:30
*Lab 7
*/
import javax.swing.JFrame;
public class THSolverFrame
{
public static void main(String[] args) throws InterruptedException
{
int numberOfDiscs = 10;
TowerOfHanoi towers = new TowerOfHanoi(numberOfDiscs);
THComponent thc = new THComponent(towers);
JFrame frame = new JFrame();
frame.setTitle("Tower of Hanoi");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(thc);
frame.setVisible(true);
//Thread.sleep(5000);
solveTower(towers, thc,numberOfDiscs);
System.out.println("DONE!!!");
}
public static void solveTower(TowerOfHanoi towers, THComponent thc, int numPlates) throws InterruptedException
{
movePlateAndUp(towers,0,numPlates,2,thc);
}
private static void movePlateAndUp(TowerOfHanoi towers, int towerfrom, int depth, int towerto, THComponent thc) throws InterruptedException
{
if(depth == 1)
{
//We are the top block
towers.moveTopDisc(towerfrom,towerto);
animate(thc);
}
else
{
//Find a tower to put everything on top of
int unusedTower = 0;
if(towerfrom == 0 || towerto == 0)
{
unusedTower = 1;
if(towerfrom == 1 || towerto == 1)
{
unusedTower = 2;
}
}
//Move everything on top of what we want to move somewhere else
movePlateAndUp(towers,towerfrom,depth-1,unusedTower,thc);
//Move us
towers.moveTopDisc(towerfrom,towerto);
animate(thc);
//Move everything that was on top of use back on top of us
movePlateAndUp(towers,unusedTower,depth-1,towerto,thc);
}
}
private static void animate(THComponent thc) throws InterruptedException
{
thc.repaint();
Thread.sleep(50);
}
}
|