import java.applet.Applet; import java.awt.*; public class card extends Applet implements Runnable { /*----------------------------------------------------*/ int LETSU[] = new int[14]; /* カードを並べる列 */ int Queue[][] = new int[94][14]; /* 探索経路を記録 */ int putQueue, getQueue; /* 探索経路を記録する(表示用) */ void action() { int i, flag=1; for (i=0; i<14; i++) { Queue[putQueue][i] = LETSU[i]; if (LETSU[i] == 0) flag = 0; } if (flag == 0) putQueue++; /* 解に達していない場合 */ } /* No.pのカードをバックトラックで置く */ /* 解が1つでも見つかれば探索を中止するようにしています */ int backtrack(int p) { int i; /* 左カードの位置 */ int j; /* 右カードの位置 */ action(); /* 状態(探索経路)の記録 */ if (p > 7) { /* 総てのカードが置かれている */ return 1; } else { for (i=0,j=p+1; j<14; i++,j++) { if (LETSU[i]==0 && LETSU[j]==0) { /* カードを置けるなら */ LETSU[i] = LETSU[j] = p; /* カードを置く */ if (backtrack(p+1) == 1) return 1; /* 次のカードへ */ LETSU[i] = LETSU[j] = 0; /* 状態を元に戻す */ } } } return 0; } /*----------------------------------------------------*/ Image buffer; Graphics grf; Thread animation = null; long sleepTime = 200; public void init() { setBackground(Color.gray); setLayout(new BorderLayout()); Panel psouth = new Panel(); psouth.add(new Button("click")); add("South", psouth); buffer = createImage(281,30); grf = buffer.getGraphics(); } public void start() { if (animation == null) { animation = new Thread(this); animation.start(); } } public void run() { long wait; while (true) { if (getQueue != putQueue) { repaint(); getQueue++; } try { animation.sleep(sleepTime); } catch (InterruptedException e) {} } } public void stop() { if (animation != null) { animation.stop(); animation = null; } } public void update(Graphics g) { paint(grf); g.drawImage(buffer,0,0,this); } public void paint(Graphics g) { int i, n; g.setColor(Color.gray); g.fillRect(0,0,280,30); g.setColor(Color.black); for (i=0; i<14; i++) g.drawRect(i*20,0,20,30); g.setFont(new Font("Helvetica",Font.BOLD,18)); for (i=0; i<14; i++) { n = Queue[getQueue][i]; if (n != 0) { switch (n) { case 1: g.setColor(Color.blue); break; case 2: g.setColor(Color.red); break; case 3: g.setColor(Color.pink); break; case 4: g.setColor(Color.green); break; case 5: g.setColor(Color.cyan); break; case 6: g.setColor(Color.yellow); break; case 7: g.setColor(Color.orange); break; } g.fillRect(i*20+2,2,16,26); g.setColor(Color.black); g.drawString(Integer.toString(n),i*20+5,22); } } } public boolean action(Event e, Object arg) { if (putQueue != getQueue) return false; if ("click".equals(arg)) { getQueue = putQueue = 0; for (int i=0; i<14; i++) Queue[0][i] = LETSU[i] = 0; backtrack(1); } return true; } }