/***************************/ /* */ /* ハノイの塔   */ /* */ /* 1997/ 5/12 宍戸 輝光 */ /* */ /***************************/ import java.awt.*; public class thanoi extends java.applet.Applet { Image bg,screen; Graphics g_bg,g_screen; int i,j,n,w,on,mov,mx,my; boolean draged,game; Panel p; Button go; Color enbanColor[]=new Color[4]; boolean enban[][]=new boolean[3][4]; public void init(){ resize(400,300); setBackground(Color.green); /*アプレットの背景を緑にする*/ setFont(new Font("TimesRoman",Font.BOLD,20)); bg=createImage(384,240); g_bg=bg.getGraphics(); screen=createImage(384,240); g_screen=screen.getGraphics(); enbanColor[0]=new Color(255,0,255); enbanColor[1]=new Color(255,0,0); enbanColor[2]=new Color(255,255,0); enbanColor[3]=new Color(0,255,255); this.setLayout((LayoutManager)null); p=new Panel(); add(p); p.reshape(100,260,200,32); p.setLayout(new FlowLayout(FlowLayout.CENTER,4,4)); go=new Button(); go.setFont(new Font("TimesRoman",Font.BOLD,12)); go.setLabel("New Game"); p.add(go); init_screen(); repaint(); } public void init_screen() { /* ゲーム初期化 */ g_bg.setColor(Color.blue); g_bg.fillRect(0,0,400,240); g_bg.setColor(Color.white); g_bg.fillRect(56,60,16,180); g_bg.fillRect(184,60,16,180); g_bg.fillRect(312,60,16,180); for (i=0;i<4;i++) enban[0][i]=true; for (i=1;i<3;i++) for(j=0;j<4;j++) enban[i][j]=false; on=-1; mov=-1; game=true; draw_enban(); } public void draw_enban() { n=0; for (i=0;i<4;i++) /* 中央の棒にある円盤の数 */ if (enban[1][i]) n++; if (n==4) { /* 4つあるならゲームクリア */ g_bg.setColor(Color.green); g_bg.drawString("C l e a r !!",128,32); game=false; } g_screen.drawImage(bg,0,0,this); /* 背景(棒)を描く */ for (i=0;i<3;i++) { /* 円盤を描く */ n=0; for (w=0;w<4;w++) /* 円盤の数を数える */ if (enban[i][w]) n++; for (j=0;j<4;j++) { /* i番めの棒に円盤を描く */ if (enban[i][j]) { g_screen.setColor(enbanColor[j]); g_screen.fillRect (i*128+64-(48+j*16)/2,240-n*32,48+j*16,32); n--; } } } if (draged) { /* 円盤移動中 */ g_screen.setColor(enbanColor[mov]); g_screen.fillRect(mx,my,48+mov*16,32); } repaint(); } public boolean mouseDown(Event evt,int x,int y) { if (x<8 ||x>391 ||y<32 ||y>248 ||on>=0 ||!game) return false; x=x-8; y=y-8; on=(int)(x/128); /* 円盤の移動元 */ i=0; for (i=0;i<4;i++) if (enban[on][i]) break; if (i==3 && !enban[on][3]) { /* 円盤がなければリターン */ on=-1; return false; } enban[on][i]=false; /* 一番上の円盤を移動 */ mov=i; /* 移動中の円盤 */ draw_enban(); return true; } public boolean mouseDrag(Event evt,int x,int y) { if (x<8 ||x>391 ||y<32 ||y>248 ||on<0) return false; draged=true; mx=x-8; my=y-8; draw_enban(); return true; } public boolean mouseUp(Event evt,int x,int y) { /* マウスアップ */ int set; if (x<8 ||x>391 ||y<8 ||y>248 ||mov<0) return false; /* スクリーン外か移動中でなければリターン */ x=x-8; /* スクリーン上の座標に変換 */ y=y-8; set=(int)(x/128); /* 新しい棒 */ for (i=0;i