//------------ // Introduction to Programming Using Java: An Object-Oriented Approach //Arnow/Weiss //------------ import java.util.*; import java.awt.*; import java.awt.event.*; import java.applet.*; class TowerDisplay extends Canvas { public TowerDisplay() { c = new Color[10]; c[0] = new Color(255,0,0); c[1] = new Color(0,255,0); c[2] = new Color(0,0,255); c[3] = new Color(255,255,0); c[4] = new Color(255,0,255); c[5] = new Color(0,255,255); c[6] = new Color(44,150,44); c[7] = new Color(44,44,150); c[8] = new Color(150,150,44); c[9] = new Color(150,44,150); } public void setup(int nDisks, int source) { if (nDisks>9) nDisks = 9; tower = new String[4]; tower[1] = "123456789".substring(0,nDisks); tower[2] = ""; tower[3] = ""; this.nDisks = nDisks; myWidth = this.getSize().width - 2*borderSize; myHeight = this.getSize().height - 2*borderSize; smallestDiskWidth = (myWidth/4) / nDisks; diskWidth = nDisks*smallestDiskWidth; interDiskWidth = diskWidth/4; diskHeight = 10; towerHeight = (nDisks+1) * diskHeight; lineLeft = borderSize + interDiskWidth; lineBot = myHeight - (myHeight- towerHeight)/2; lineWidth = 3*diskWidth + 2*interDiskWidth; lineRight = lineLeft+lineWidth; towerLeft = new int[4]; towerLeft[1] = lineLeft + diskWidth/2; towerLeft[2] = towerLeft[1] + diskWidth/2 + interDiskWidth + diskWidth/2; towerLeft[3] = towerLeft[2] + diskWidth/2 + interDiskWidth + diskWidth/2; paint(this.getGraphics()); delay(1000); } public void setDelay(int d) { sdelay = d; } public void displayMove(int from, int to) { Graphics g = this.getGraphics(); int fromLast = tower[from].length()-1; Color c = getDiskColor(from,fromLast); tower[to] = tower[to].concat(tower[from]. substring(fromLast)); tower[from] = tower[from]. substring(0,fromLast); paintLowerBackground(g); g.setColor(c); g.setFont(new Font("Helvetica",Font.BOLD,18)); g.drawString("Move from "+from+" to "+to, lineLeft,myHeight - (myHeight- towerHeight)/4); delay(sdelay); paint(g); delay(sdelay/3); } public void update(Graphics g) { paint(g); } public void paint(Graphics g) { paintBackground(g); paintBorder(g); g.setColor(new Color(0,0,0)); if (tower==null) return; g.drawLine(lineLeft,lineBot,lineRight,lineBot); paintTower(g,1); paintTower(g,2); paintTower(g,3); } private void paintTower(Graphics g, int whichTower) { int j; String s = tower[whichTower]; g.setColor(new Color(0,0,0)); g.drawLine(towerLeft[whichTower],lineBot, towerLeft[whichTower],lineBot-towerHeight); for (int i=0;i