/****************************************/ /*                   */ /*   15ゲームを作る第二回     */ /*                   */ /* 1998/ 6/14 宍戸 輝光     */ /*                   */ /****************************************/ import java.awt.*; import java.util.Random; public class g152 extends java.applet.Applet { // メインクラス Button nob[][]=new Button[4][4]; Button clb; int ban[][]=new int[4][4]; Panel bp,p,cp; public void init(){ int i,j; setBackground(Color.white); setLayout(new BorderLayout()); bp=new Panel(); bp.setBackground(Color.white); p=new Panel(); // 磐面用パネル作成 p.setBackground(Color.gray); // 灰色にする cp=new Panel(); cp.setBackground(Color.white); p.setLayout(new GridLayout(4,4,2,2)); // 磐面のレイアウト for (i=0;i<4;i++) // ボタン作成 for (j=0;j<4;j++) { nob[j][i]=new Button(); // ボタン作成 p.add(nob[j][i]); // 磐面にボタン配置 ban[j][i]=j+i*4+1; // 磐面情報初期設定 } ban[3][3]=0; bp.add(p); clb=new Button("Clear!"); // Clear ボタン配置 cp.add(clb); add("Center",bp); // 磐面をアプレットに配置 add("South",cp); clearGame(); // 乱数で磐面情報作成 drawBan(); // 磐面描画 } public void drawBan() { // 磐面描画 int i,j; for (i=0;i<4;i++) // 各マスの駒を調べ、ボタンに反映 for (j=0;j<4;j++) { // (j,i) のマスを調べる if (ban[j][i]==0) // 駒がなければ nob[j][i].show(false); else { // 駒の数字をボタンの文字にする nob[j][i].setLabel (String.valueOf(ban[j][i])); nob[j][i].show(true); } } repaint(); } public void clearGame() { int i,x1,y1,x2,y2,w; Random rnd=new Random(); for (i=0;i<20;i++) { // 乱数で各マスを入れ替える x1=Math.abs(rnd.nextInt()) % 4; y1=Math.abs(rnd.nextInt()) % 4; x2=Math.abs(rnd.nextInt()) % 4; y2=Math.abs(rnd.nextInt()) % 4; w=ban[x1][y1]; // (x1 ,y1) と(x2 ,y2) を交換 ban[x1][y1]=ban[x2][y2]; ban[x2][y2]=w; } } public boolean action(Event evt,Object What) { if (evt.target==clb) { // Clear ボタン clearGame(); drawBan(); return true; } return false; } }