日期:2014-05-20  浏览次数:20812 次

java韩顺平老师的坦克程序,无法实现坦克的运动(在线等 谢谢高手)

/*
 *控制坦克的泡铜方向
 *
 */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class MyTankGame3 extends JFrame {

  Mypanel mp = null;

public static void main(String[] args) {
MyTankGame3 mtg = new MyTankGame3();

}

// 构造函数
public MyTankGame3() {
mp = new Mypanel();
this.add(mp);
// 注册监听
this.addKeyListener(mp);
this.setSize(400, 300);
  //this.setLocation(50,50);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  this.setVisible(true);
}
}

// 我的面板
class Mypanel extends JPanel implements KeyListener {
// 定义一个我的坦克
Hero hero = null;

// 定义一个敌人的坦克组
Vector<EnemyTank> ets = new Vector<EnemyTank>();
int enSize = 3;

// 构造函数
public Mypanel() {

  hero = new Hero(150, 150);
   
// 初始化敌人的坦克
for (int i = 1; i <= enSize; i++) 
  {
// 创建一辆敌人的坦克
  EnemyTank et = new EnemyTank((i + 1) * 50, 15);
et.setColor(0); 
et.setDirect(2);
// 加入到敌人坦克组中
ets.add(et);
}
}

public void paint(Graphics g) {

super.paint(g);
  //设置背景颜色,400,300为窗体的长宽
g.fillRect(0, 0, 400, 300);
// 调用drawTank()传递系列参数
this.drawTank(hero.getX(), hero.getY(), g, hero.direct, 1);
// 画出敌人的坦克 很多辆 不确定
for (int i = 0; i <= ets.size(); i++) {
this.drawTank(ets.get(i).getX() , ets.get(i).getY(), g, ets.get(i)
.getDirect(), 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 - 10, y - 15, 5, 30, false);
// 2.画出右边的矩形
g.fill3DRect(x + 5, y - 15, 5, 30, false);
// 3.画出中间矩形
g.fill3DRect(x - 5, y - 10, 10, 20, false);
// 4.画出圆形
g.fillOval(x - 5, y - 5, 10, 10);
// 5.画出线
g.drawLine(x, y, x, y - 15);
break;
// 向右
case 1:
// 1.画出上边的矩形
g.fill3DRect(x - 15, y - 10, 30, 5, false);
// 2.画出下边的矩形
g.fill3DRect(x - 15, y + 5, 30, 5, false);
// 3.画出中间矩形
g.fill3DRect(x - 10, y - 5, 20, 10, false);
// 4.画出圆形
g.fillOval(x - 5, y - 5, 10, 10);
// 5.画出线
g.drawLine(x, y, x + 15, y);
break;
// 向下
case 2:
// 1.画出左边的矩形
g.fill3DRect(x - 10, y - 15, 5, 30, false);
// 2.画出右边的矩形
g.fill3DRect(x + 5, y - 15, 5, 30, false);
// 3.画出中间矩形
g.fill3DRect(x - 5, y - 10, 10, 20, false);
// 4.画出圆形
g.fillOval(x - 5, y - 5, 10, 10);
// 5.画出线
g.drawLine(x, y, x, y + 15);
break;
// 向左
case 3:
// 1.画出上边的矩形
g.fill3DRect(x - 15, y - 10, 30, 5, false);
// 2.画出下边的矩形
g.fill3DRect(x - 15, y + 5, 30, 5, false);
// 3.画出中间矩形
g.fill3DRect(x - 10, y - 5, 20, 10, false);
// 4.画出圆形
g.fillOval(x - 5, y - 5, 10, 10);
// 5.画出线
g.drawLine(x, y, x - 15, y);
break;

}
}

// 键按下处理,a表示向左,s表示向下,d表示向右,w表示向上
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
if (arg0.getKeyCode() == KeyEvent.VK_W) {
// 设置我的坦克的方向
this.hero.setDirect(0);
if (this.hero.y > 15) {
this.hero.moveUp();
}
} else if (arg0.getKeyCode() == KeyEvent.VK_D) {