思路:写出我方坦克的上下左右的移动方法,在MyPanel类里继承Keylistener接口,重写三个方法
在KeyPressed方法中写出上写左右四个动作对应的四个方向,和方法,然后重绘
MyPanel类:
import javafx.scene.input.KeyCode;
import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.*;
import java.util.Vector;
public class MyPanel extends Panel implements KeyListener {
MyTank myTank = null;
Vector enemyTanks = new Vector();//集合类
int enemynum = 12;//坦克数量
MyPanel() {
myTank = new MyTank(120, 220);//初始化我的坦克的初始坐标
myTank.setSpeed(5);
for (int i = 0; i < enemynum / 2; i++) {
EnemyTank enemyTank = new EnemyTank(i * (230 + 5), 0);//给上面的enemyTank初始化坐标
enemyTanks.add(enemyTank);//向集合里面添加enemyTank
}
for (int i = 6; i < enemynum; i++) {
EnemyTank enemyTank = new EnemyTank((12 - i - 1) * (230 + 5), 930);//给下面的enemyTank初始化坐标
enemyTanks.add(enemyTank);
}
}
public void paint(Graphics g) //重写paint方法
{
g.setColor(Color.black);//画笔着色
g.fillRect(0, 0, 1200, 1000);//面板
if (myTank.life) {
drawTank(myTank.getX(), myTank.getY(), myTank.getDir(), g, 0);//画我方坦克
}
for (int i = 0; i < enemyTanks.size(); i++) {
EnemyTank enemyTank = enemyTanks.get(i);
drawTank(enemyTank.getX(), enemyTank.getY(), enemyTank.getDir(), g, 1);//画敌方坦克
}
}
public void drawTank(int x, int y, int dir, Graphics g, int type)//画坦克
{
//System.out.println(dir);
switch (type) {
case 0://我方
g.setColor(Color.red);
break;
case 1://敌方
g.setColor(Color.green);
break;
}
switch (dir) {
case 0://上
g.fill3DRect(x, y, 5, 30, false);//左腿
g.fill3DRect(x + 15, y, 5, 30, false);//右腿
g.fill3DRect(x + 5, y + 5, 10, 20, false);//中间
g.fillOval(x + 5, y + 10, 10, 10);//圆形
g.drawLine(x + 10, y + 15, x + 10, y - 3);//炮管
break;
case 1://左
g.fill3DRect(x, y, 30, 5, false);
g.fill3DRect(x, y + 15, 30, 5, false);
g.fill3DRect(x + 5, y + 5, 20, 10, false);
g.fillOval(x + 10, y + 5, 10, 10);
g.drawLine(x + 15, y + 10, x - 3, y + 10);
break;
case 2://下
g.fill3DRect(x, y, 5, 30, false);
g.fill3DRect(x + 15, y, 5, 30, false);
g.fill3DRect(x + 5, y + 5, 10, 20, false);
g.fillOval(x + 5, y + 10, 10, 10);
g.drawLine(x + 10, y + 15, x + 10, y + 33);
break;
case 3://右
g.fill3DRect(x, y, 30, 5, false);
g.fill3DRect(x, y + 15, 30, 5, false);
g.fill3DRect(x + 5, y + 5, 20, 10, false);
g.fillOval(x + 10, y + 5, 10, 10);
g.drawLine(x + 15, y + 10, x + 33, y + 10);
break;
}
}
public void keyReleased(KeyEvent e){};
public void keyTyped(KeyEvent e){};
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==KeyEvent.VK_W)
{
myTank.up();
myTank.setDir(0);
}
else if(e.getKeyCode()==KeyEvent.VK_S)
{
myTank.down();
myTank.setDir(2);
}
else if(e.getKeyCode()==KeyEvent.VK_A)
{
myTank.left();
myTank.setDir(1);
}
else if(e.getKeyCode()==KeyEvent.VK_D)
{
myTank.right();
myTank.setDir(3);
}
this.repaint();
}
}
MyTank类:
public class MyTank extends Tank {
MyTank(int x,int y)
{
super(x,y);
}
public void up()
{
setY(getY()-getSpeed());
}
public void down()
{
setY(getY()+getSpeed());
}
public void left()
{
setX(getX()-getSpeed());
}
public void right()
{
setX(getX()+getSpeed());
}
}