`
wanchong998
  • 浏览: 232876 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

汉诺塔程序的j2me实现(触摸屏)

    博客分类:
  • J2me
阅读更多
汉诺塔程序的j2me实现(触摸屏)

import javax.microedition.lcdui.Display;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class Hanoi extends MIDlet {
Display display;
MyCanvas canvas;

public Hanoi() {
  display = Display.getDisplay(this);
  canvas = new MyCanvas();
}

protected void destroyApp(boolean arg0) throws MIDletStateChangeException {

}

protected void pauseApp() {

}

protected void startApp() throws MIDletStateChangeException {
  display.setCurrent(canvas);
}

}


Canvas:

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;

public class MyCanvas extends Canvas {
public int width, height;
public int w, h;
public final int max = 7;
public int px[];
public Stack[] pos;

public int select = -1;

public MyCanvas() {
  setFullScreenMode(true);
  width = getWidth();
  height = getHeight();
  w = width / 3;
  h = height / max / 2;
  px = new int[] { w / 2, w * 3 / 2, w * 5 / 2 };
  pos = new Stack[3];
  pos[0] = new Stack(max);
  pos[1] = new Stack(max);
  pos[2] = new Stack(max);
  for (int i = max; i > 0; i--) {
   pos[0].push(i);
  }
}

protected void paint(Graphics g) {
  g.setColor(0xffffff);
  g.fillRect(0, 0, width, height);
  g.setColor(0);
  for (int j = 0; j < 3; j++) {
   g.drawLine(px[j], height / 2, px[j], height);
   for (int i = 0, len = pos[j].size(); i < len; i++) {
    int v = pos[j].get(i);
    g.drawRect(px[j] - w * v / max / 2, height - (i + 1) * h, w * v
      / max, h);
   }
  }
}

protected void pointerPressed(int x, int y) {
  if (select != -1) {
   if (select != x / w) {
    move(select, x / w);
    select = -1;
   }
  } else {
   select = x / w;
  }
}

public void move(int from, int to) {
  System.out.println("from:" + from + "   to:" + to);
  int f;
  int t;
  if (pos[from].isEmpty()) {
   f = 0;
  } else {
   f = pos[from].peek();
  }
  if (pos[to].isEmpty()) {
   t = 0;
  } else {
   t = pos[to].peek();
  }
  System.out.println(f + "," + t);

  if (t == 0) {
   pos[from].pop();
   pos[to].push(f);
  } else if (t > f) {
   pos[from].pop();
   pos[to].push(f);
  } else {
   System.out.println("不能移动");
  }
  repaint();
}

}



Stack:

public class Stack {
public final int SIZE;
public int[] st;
public final int Bottom;
public int top;

public Stack(int size) {
  SIZE = size;
  st = new int[SIZE];
  top = Bottom = 0;
}

public void push(int v) {
  st[top] = v;
  top++;
}

public int pop() {
  return st[--top];
}

public int peek() {
  if (isEmpty()) {
   return 0;
  }
  return st[top - 1];
}

public boolean isEmpty() {
  return top == Bottom;
}

public int size() {
  return top;
}

public int get(int index) {
  return st[index];
}

public boolean isFull() {
  return top == Bottom;
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics