TankGame package com.tank02;import java.awt.*;import java.awt.event.*;import java.awt.event.KeyListener;import javax.swing.*;public class TankBattle2 extends JFrame{//定义面板MyPanel mp = null;public static void main(String[] args){Tank
package com.tank02; import java.awt.*; import java.awt.event.*; import java.awt.event.KeyListener; import javax.swing.*; public class TankBattle2 extends JFrame{ //定义面板 MyPanel mp = null; public static void main(String[] args){ TankBattle2 tb = new TankBattle2(); } //构造函数 public TankBattle2(){ mp = new MyPanel(); this.add(mp); this.setSize(400, 300); //注册监听 this.addKeyListener(mp); //防止内存泄漏 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } } //面板类 class MyPanel extends JPanel implements KeyListener{ //定义我的坦克 MyTank mt = null; int x, y; //构造函数 public MyPanel(){ mt = new MyTank(100, 100); } //重写paint方法 public void paint(Graphics g){ super.paint(g); g.fillRect(0, 0, 400, 300); this.drawTank(this.mt.getX(), this.mt.getY(), g, 0, 0); } //画坦克的函数 public void drawTank(int x, int y, Graphics g, int direct, int type){ //坦克类型 switch(type){ case 0: g.setColor(Color.CYAN); break; case 1: g.setColor(Color.yellow); break; } //坦克方向 switch(direct){ //向上 case 0: //1.画出左面的矩形 g.fill3DRect(x, y, 5, 30, false); //2.画出右边的矩形 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); break; } } @Override //键按下处理:a表示向左,s表示向下,d表示向右,w表示向上 public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_W){ //设置我的坦克的方向 this.mt.setDirect(0); this.mt.moveUp(); }else if(e.getKeyCode() == KeyEvent.VK_D){ //向右 this.mt.setDirect(1); this.mt.moveRight(); }else if(e.getKeyCode() == KeyEvent.VK_S){ //向下 this.mt.setDirect(2); this.mt.moveDown(); }else if(e.getKeyCode() == KeyEvent.VK_A){ //向左 this.mt.setDirect(3); this.mt.moveLeft(); } //调用repaint函数,来重绘界面 this.repaint(); } @Override public void keyReleased(KeyEvent e) { // TODO 自动生成的方法存根 } @Override public void keyTyped(KeyEvent e) { // TODO 自动生成的方法存根 } } //坦克类 class Tank { //坦克的横坐标 int x; //坦克的纵坐标 int y; //坦克方向 //0表示上,1表示右,2表示下,3表示左 int direct = 0; //坦克的速度 int speed = 10; public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } public int getDirect() { return direct; } public void setDirect(int direct) { this.direct = direct; } //setter和getter方法 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 Tank(int x, int y){ this.x = x; this.y = y; } } //我的坦克类 class MyTank extends Tank{ public MyTank(int x, int y){ super(x, y); } //坦克向上移动 public void moveUp(){ this.y -= speed; } //坦克向右移动 public void moveRight(){ this.x += speed; } //向下移动 public void moveDown(){ this.y += speed; } //向左 public void moveLeft(){ this.x -= speed; } }