⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 hanoi.java

📁 一个演示汉诺塔的JavaApplet小程序
💻 JAVA
字号:
/*
 * @(#)Hanoi.java 1.0 03/05/09
 *
 * You can modify the template of this file in the
 * directory ..\JCreator\Templates\Template_2\Project_Name.java
 *
 * You can also create your own project template by making a new
 * folder in the directory ..\JCreator\Template\. Use the other
 * templates as examples.
 *
 */

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


public class Hanoi extends Applet implements Runnable {
	static public int delay = 300;
	int n_plate = 5;
	Graphics g;
	private Thread hanoi_thread;
	boolean thread_run = false;
	boolean flag_down[][] = new boolean[4][n_plate+1];
	
	
	public void init() {
		g = getGraphics();
	}
	
	public void stop() {
		hanoi_thread.stop();
		hanoi_thread = null;
	}
	
	public boolean mouseUp(Event evt, int x, int y){
		if (! thread_run || ! hanoi_thread.isAlive()) {
			hanoi_thread = new Thread(this);
			hanoi_thread.start();
			thread_run = true;
			for (int i=0; i<=3; i++)
				for (int j=0; j<=n_plate; j++)
					flag_down[i][j] = true;
			repaint();
		}
		return true;
	}
	public void run() {
		move(n_plate, 1, 2, 3);
	}

	public void paint(Graphics g) {
		g.setColor(Color.lightGray);
		g.fillRect(0,0,510,200);
		mast();
		for (int i=1; i<=n_plate; i++) {
			print_plate(1,i,i);
			flag_down[1][i] = false;
		}
	}
	
	public void move(int n, int a, int b, int c) {
		if (n == 1) {
			delay();
			int i=1;
			while (flag_down[a][i]) {
				i++;
			}
			flag_down[a][i] = true;
			rubber_plate(a,i,n);			
			
			delay();
		 	i=n_plate;
			while (!flag_down[c][i]) {
				i--;
			}
			flag_down[c][i] = false;
			
			print_plate(c,i,n);
			
		}
		else {
			move(n-1, a, c, b);
			
			delay();
			int i=1;
			while (flag_down[a][i]) {
				i++;
			}
			flag_down[a][i] = true;
			rubber_plate(a,i,n);			
			
			
			delay();
			i=n_plate;
			while (!flag_down[c][i]) { 
				i--;
			}
			flag_down[c][i] = false;
		
			print_plate(c,i,n);
			
			move(n-1, b, a, c);
		}
	}
	
	//画柱子
	public void mast() {
		g.setColor(Color.black);
		for (int i=0; i<=2; i++)
			g.fillRoundRect( i*160+88,30,12,120,5,5);
		g.fillRoundRect(10,140,490,15,5,5);
	}
	
	//画盘子(位置(x,y),大小size);
	public void print_plate(int x, int y, int size) {
		y = n_plate-y+1;
		size = size*20+50;
		g.setColor(new Color(200-size,200-size,200-size));
		g.fillRoundRect((x-1)*160+88-size/2+6, 140-(y*15), size, 15, 16, 16);
	}
	
	//除盘子(位置(x,y),大小size);
	public void rubber_plate(int x, int y, int size) {
		y = n_plate-y+1;
		size = size*20+50;
		g.setColor(Color.lightGray);
		g.fillRoundRect((x-1)*160+88-size/2+6, 140-(y*15), size, 15, 16, 16);
		g.setColor(Color.black);
		g.fillRect((x-1)*160+88,140-(y*15),12,15);
	}
	
	//时延		
	void delay() {
		try {
			Thread.sleep(Hanoi.delay);
		}
		catch(InterruptedException e){
		}
	}
	
	
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -