黑马程序员技术交流社区
标题:
为什么我的坦克一闪一闪的
[打印本页]
作者:
sixth
时间:
2012-11-5 22:22
标题:
为什么我的坦克一闪一闪的
import java.awt.*;
import java.awt.event.*;
public class TankGame extends Frame{
Hero hero = new Hero(280,550,0);
public static void main(String args[]) {
new TankGame();
}
public TankGame() {
this.setSize(600,600);
this.setBackground(Color.BLACK);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
this.setVisible(true);
this.addKeyListener(new KeyMonitor());
}
public void paint(Graphics g) {
//画出主坦克
g.setColor(Color.YELLOW);
switch(hero.direct) {
case 0:
g.fill3DRect(hero.x, hero.y, 10, 40,false );
g.fill3DRect(hero.x+30, hero.y, 10, 40, false);
g.fill3DRect(hero.x+10, hero.y+10, 20, 20, false);
g.fillOval(hero.x+15, hero.y+10, 10, 10);
g.fillRect(hero.x+18, hero.y, 4, 10);
break;
case 1:
g.fill3DRect(hero.x, hero.y, 40, 10,false );
g.fill3DRect(hero.x, hero.y+30, 40, 10, false);
g.fill3DRect(hero.x+10, hero.y+10, 20, 20, false);
g.fillOval(hero.x+20, hero.y+15, 10, 10);
g.fillRect(hero.x+30, hero.y+18, 10, 4);
break;
case 2:
g.fill3DRect(hero.x, hero.y, 10, 40,false );
g.fill3DRect(hero.x+30, hero.y, 10, 40, false);
g.fill3DRect(hero.x+10, hero.y+10, 20, 20, false);
g.fillOval(hero.x+15, hero.y+20, 10, 10);
g.fillRect(hero.x+18, hero.y+30, 4, 10);
break;
case 3:
g.fill3DRect(hero.x, hero.y, 40, 10,false );
g.fill3DRect(hero.x, hero.y+30, 40, 10, false);
g.fill3DRect(hero.x+10, hero.y+10, 20, 20, false);
g.fillOval(hero.x+10, hero.y+15, 10, 10);
g.fillRect(hero.x, hero.y+18, 10, 4);
break;
}
repaint();
}
class KeyMonitor extends KeyAdapter {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_W) {
hero.setDirect(0);
hero.moveUp();
}
else if(e.getKeyCode() == KeyEvent.VK_D) {
hero.setDirect(1);
hero.moveRight();
}
else if(e.getKeyCode() == KeyEvent.VK_S) {
hero.setDirect(2);
hero.moveDown();
}
else if(e.getKeyCode() == KeyEvent.VK_A) {
hero.setDirect(3);
hero.moveLeft();
}
}
}
}
坦克类:
public class Tank {
int x,y;
int speed = 2;
int direct;
Tank(int x,int y) {
this.x = x;
this.y = y;
}
public int getDirect() {
return direct;
}
public void setDirect(int direct) {
this.direct = direct;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
class Hero extends Tank {
public Hero(int x,int y,int direct) {
super(x,y);
this.direct = direct;
}
public void moveUp() {
y -= speed;
}
public void moveRight() {
x += speed;
}
public void moveDown() {
y += speed;
}
public void moveLeft() {
x -= speed;
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2