用JAVA写一个坦克大战游戏
时间: 2023-07-01 09:08:48 浏览: 84
好的,下面是一个简单的坦克大战游戏的JAVA代码示例:
```java
import java.awt.*;
import java.awt.event.*;
public class TankWar extends Frame {
private static final long serialVersionUID = 1L;
public static final int GAME_WIDTH = 800;
public static final int GAME_HEIGHT = 600;
Tank myTank = new Tank(50, 50, true, this);
Tank enemyTank = new Tank(700, 500, false, this);
public TankWar() {
setSize(GAME_WIDTH, GAME_HEIGHT);
setTitle("Tank War");
setResizable(false);
setVisible(true);
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
myTank.keyPressed(e);
enemyTank.keyPressed(e);
}
public void keyReleased(KeyEvent e) {
myTank.keyReleased(e);
enemyTank.keyReleased(e);
}
});
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void paint(Graphics g) {
myTank.draw(g);
enemyTank.draw(g);
}
public static void main(String[] args) {
new TankWar();
}
}
class Tank {
private static final int SPEED = 5;
private int x;
private int y;
private boolean isGood;
private boolean isUp;
private boolean isDown;
private boolean isLeft;
private boolean isRight;
private TankWar tw;
public Tank(int x, int y, boolean isGood, TankWar tw) {
this.x = x;
this.y = y;
this.isGood = isGood;
this.tw = tw;
}
public void draw(Graphics g) {
Color c = g.getColor();
if (isGood) g.setColor(Color.RED);
else g.setColor(Color.BLUE);
g.fillOval(x, y, 30, 30);
g.setColor(c);
move();
}
private void move() {
if (isUp) y -= SPEED;
if (isDown) y += SPEED;
if (isLeft) x -= SPEED;
if (isRight) x += SPEED;
}
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
isUp = true;
break;
case KeyEvent.VK_DOWN:
isDown = true;
break;
case KeyEvent.VK_LEFT:
isLeft = true;
break;
case KeyEvent.VK_RIGHT:
isRight = true;
break;
}
}
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
isUp = false;
break;
case KeyEvent.VK_DOWN:
isDown = false;
break;
case KeyEvent.VK_LEFT:
isLeft = false;
break;
case KeyEvent.VK_RIGHT:
isRight = false;
break;
}
}
}
```
这个示例是一个简单的坦克大战游戏,只有两个坦克,分别由玩家和电脑控制,可以通过方向键控制坦克移动。你可以在此基础上进行修改和扩展,增加更多的游戏功能。
阅读全文