class MyGameCanvas extends GameCanvas implements Runnable{
private TiledLayer troad;
private TiledLayer twall;
private Sprite sperson;
private Image personImage;
private Image mapImage;
private LayerManager lm;
private Graphics g;
protected MyGameCanvas(boolean suppressKeyEvents) {
super(true);
try {
lm=new LayerManager();
g=this.getGraphics();
personImage=Image.createImage("/icon.png");
mapImage=Image.createImage("/map.png");
sperson=new Sprite(personImage);
troad=new TiledLayer(4, 2, mapImage, mapImage.getWidth()/2, mapImage.getHeight());
twall=new TiledLayer(4, 2, mapImage, mapImage.getWidth()/2, mapImage.getHeight());
twall.setPosition(0, 80);
troad.setCell(0, 0, 1);
troad.setCell(1, 0, 1);
troad.setCell(2, 0, 1);
troad.setCell(3, 0, 1);
troad.setCell(0, 1, 1);
troad.setCell(1, 1, 1);
troad.setCell(2, 1, 1);
troad.setCell(3, 1, 1);
twall.setCell(0, 0, 2);
twall.setCell(1, 0, 2);
twall.setCell(2, 0, 2);
twall.setCell(3, 0, 2);
twall.setCell(0, 1, 2);
twall.setCell(1, 1, 2);
twall.setCell(2, 1, 2);
twall.setCell(3, 1, 2);
lm.append(sperson);
lm.append(troad);
lm.append(twall);
lm.setViewWindow(0, 0, this.getWidth(), this.getHeight());
lm.paint(g, 0, 0);
this.flushGraphics();
new Thread(this).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
while(true){
g.setColor(255, 255, 255);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
lm.paint(g, 0, 0);
this.flushGraphics();
switch (this.getKeyStates()) {
case DOWN_PRESSED:
System.out.println("下");
if (!sperson.collidesWith(twall, true))
{
sperson.move(0, 1);
}else{
System.out.println("撞墙了");
}
lm.paint(g, this.getWidth(), this.getHeight());
this.flushGraphics();
break;
case UP_PRESSED :
System.out.println("上");
sperson.move(0, -1);
if (sperson.collidesWith(twall, true))
{
System.out.println("撞墙了");
}
lm.paint(g, this.getWidth(), this.getHeight());
this.flushGraphics();
break;
case LEFT_PRESSED :
System.out.println("左");
sperson.move(-1, 0);
if (sperson.collidesWith(twall, true))
{
System.out.println("撞墙了");
}
lm.paint(g, this.getWidth(), this.getHeight());
this.flushGraphics();
break;
case RIGHT_PRESSED:
System.out.println("右");
sperson.move(1, 0);
if (sperson.collidesWith(twall, true))
{
System.out.println("撞墙了");
}
lm.paint(g, this.getWidth(), this.getHeight());
this.flushGraphics();
break;
}
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
运行效果: