用java实现坦克大战
时间: 2023-10-02 22:08:13 浏览: 94
坦克大战是一款经典的游戏,使用Java实现也是可行的。下面是一个简单的Java实现坦克大战的示例代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TankGame extends JFrame {
private Tank tank;
private Missile missile;
public TankGame() {
this.setSize(500, 500);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addKeyListener(new KeyMonitor());
tank = new Tank(50, 50);
missile = new Missile(tank.x, tank.y, tank.dir);
}
public void paint(Graphics g) {
super.paint(g);
tank.draw(g);
missile.draw(g);
}
class KeyMonitor extends KeyAdapter {
public void keyPressed(KeyEvent e) {
tank.moving = true;
switch(e.getKeyCode()) {
case KeyEvent.VK_UP:
tank.dir = Dir.UP;
break;
case KeyEvent.VK_DOWN:
tank.dir = Dir.DOWN;
break;
case KeyEvent.VK_LEFT:
tank.dir = Dir.LEFT;
break;
case KeyEvent.VK_RIGHT:
tank.dir = Dir.RIGHT;
break;
}
}
public void keyReleased(KeyEvent e) {
tank.moving = false;
}
}
class Tank {
public static final int SPEED = 5;
public int x, y;
public boolean moving = false;
public Dir dir = Dir.DOWN;
public Tank(int x, int y) {
this.x = x;
this.y = y;
}
public void draw(Graphics g) {
g.fillRect(x, y, 30, 30);
if (moving) {
switch (dir) {
case UP:
y -= SPEED;
break;
case DOWN:
y += SPEED;
break;
case LEFT:
x -= SPEED;
break;
case RIGHT:
x += SPEED;
break;
}
}
}
}
class Missile {
public static final int SPEED = 10;
public int x, y;
public Dir dir;
public Missile(int x, int y, Dir dir) {
this.x = x;
this.y = y;
this.dir = dir;
}
public void draw(Graphics g) {
g.setColor(Color.RED);
g.fillOval(x, y, 10, 10);
switch (dir) {
case UP:
y -= SPEED;
break;
case DOWN:
y += SPEED;
break;
case LEFT:
x -= SPEED;
break;
case RIGHT:
x += SPEED;
break;
}
}
}
enum Dir {
UP,
DOWN,
LEFT,
RIGHT
}
public static void main(String[] args) {
new TankGame();
}
}
```
这个示例程序中,我们实现了一个可以用方向键控制移动的坦克,以及一个可以沿着坦克方向移动的导弹。你可以在这个基础上增加更多功能,比如增加敌人坦克、增加障碍物、增加爆炸效果等等。
阅读全文