🛫创建父类坦克类
- 🪂🪂🪂这个类是作为以后创建自己的坦克和敌人的坦克的子类
- 实现很简单 主要是定义一些属性
- 坦克的位置
- 坦克的速度
- 坦克的方向
public class Tank { //面向对象!!!!!!!充分体现 private int x; private int y; private int direct; private int speed =1; public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } public void moveUp(){ y-=speed; } public void moveDown(){ y+=speed; } public void moveLeft(){ x-=speed; } public void moveRight(){ x+=speed; } public int getDirect() { return direct; } public void setDirect(int direct) { this.direct = direct; } public Tank(int direct) { this.direct = direct; } public Tank(int x, int y) { this.x = x; this.y = y; } 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; } }
🚍创建自己坦克
public class Hero extends Tank {
public Hero(int x, int y) {
super(x, y);
}
}
🏃♂️🏃♂️🏃♂️动起来
要想让坦克动起来,必须要在我们定义的画板类上实现一个接口
事件监听机制
public class Mypanel extends JPanel implements KeyListener{}
然后要实现他的所有方法,但是我们这个需求用到的只有其中的一个方法
@Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { if(e.getKeyCode()==KeyEvent.VK_W){ if(hero.getY()>0){ hero.moveUp(); } hero.setDirect(0); } else if (e.getKeyCode()==KeyEvent.VK_D) { if(hero.getX()+60<1000){ hero.moveRight(); } hero.setDirect(1); } else if (e.getKeyCode()==KeyEvent.VK_S) { if (hero.getY()+60<750){ hero.moveDown(); } hero.setDirect(2); }else if (e.getKeyCode()==KeyEvent.VK_A) { if (hero.getX()>0){ hero.moveLeft(); } hero.setDirect(3); } this.repaint(); 注意!!! 🌈🌈🌈🌈🌈 这行代码是重点!千万不要忘记写!!! 上一篇博客我说过,paint方法被系统调用的条件,其中重绘就会被自动调用,所以说当我们每次按完键盘按键的时候都需要再次调用一下画板重绘的操作,这样才能看到坦克动态移动的效果,如果没有这个重绘的方法调用,是没有办法看到动态效果的,只会看到坦克再原地不停的旋转 } @Override public void keyReleased(KeyEvent e) { }
- 🕵️♀️🕵️♀️🕵️♀️最后一点不要忘记,要把 这个事件监听机制添加到我们的框架中,因为我们所做的一切都是基于JFrame框架实现的,所以在Tank的构造方法中要加上事件监听机制 才能生效
public TankGame03() {
mp=new Mypanel();
this.add(mp);
🚕🚕🚕
this.addKeyListener(mp);//在框架中添加事件监听机制
🚓🚓🚓
this.setSize(1030,810);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}