java代码实现飞机大战
时间: 2023-11-16 11:04:27 浏览: 64
以下是一个简单的飞机大战游戏的 Java 代码实现:
```
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
public class PlaneWar extends JFrame implements KeyListener, Runnable {
private int width = 400; // 游戏窗口宽度
private int height = 600; // 游戏窗口高度
private int x = 180, y = 500; // 我方飞机初始位置
private int dx = 0; // 我方飞机水平移动速度
private int dy = 0; // 我方飞机垂直移动速度
private int bx = 0, by = -1; // 子弹位置和速度
private int ex = 150, ey = 50; // 敌方飞机位置
private BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
private Graphics g = image.createGraphics();
private boolean gameOver = false; // 游戏结束标志
private Thread thread;
public PlaneWar() {
setSize(width, height);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
addKeyListener(this);
thread = new Thread(this);
thread.start();
}
public void run() {
while (!gameOver) {
movePlane();
moveBullet();
moveEnemy();
checkOverlap();
repaint();
try { Thread.sleep(10); } catch (Exception e) {}
}
}
private void movePlane() {
x += dx;
y += dy;
if (x < 0) x = 0;
if (x > width - 30) x = width - 30;
if (y < 0) y = 0;
if (y > height - 50) y = height - 50;
}
private void moveBullet() {
by -= 5;
}
private void moveEnemy() {
ey += 2;
if (ey > height) {
ex = (int) (Math.random() * (width - 30));
ey = -30;
}
}
private void checkOverlap() {
Rectangle bulletRect = new Rectangle(bx, by, 3, 10);
Rectangle enemyRect = new Rectangle(ex, ey, 30, 30);
if (bulletRect.intersects(enemyRect)) {
bx = x + 13;
by = y - 10;
ex = (int) (Math.random() * (width - 30));
ey = -30;
}
Rectangle planeRect = new Rectangle(x, y, 30, 50);
if (planeRect.intersects(enemyRect)) {
gameOver = true;
}
}
public void paint(Graphics g) {
g.drawImage(image, 0, 0, null);
g.setColor(Color.RED);
g.fillRect(ex, ey, 30, 30);
g.setColor(Color.BLUE);
g.fillRect(x, y, 30, 50);
g.setColor(Color.BLACK);
g.fillRect(bx, by, 3, 10);
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) dx = -3;
if (key == KeyEvent.VK_RIGHT) dx = 3;
if (key == KeyEvent.VK_UP) dy = -3;
if (key == KeyEvent.VK_DOWN) dy = 3;
if (key == KeyEvent.VK_SPACE) {
bx = x + 13;
by = y - 10;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT || key == KeyEvent.VK_RIGHT) dx = 0;
if (key == KeyEvent.VK_UP || key == KeyEvent.VK_DOWN) dy = 0;
}
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
new PlaneWar();
}
}
```
在以上代码中,我们使用了 Java 的 AWT 和 Swing 库来实现游戏界面和用户交互。主要的游戏逻辑实现在 `run()` 方法中,每次循环更新飞机、子弹和敌机的位置,检查是否有重叠,并在最后重绘界面。`paint()` 方法则是用来绘制游戏界面的。`keyPressed()` 和 `keyReleased()` 方法监听用户输入的按键事件,来控制飞机的移动和发射子弹。`main()` 方法是程序的入口,创建一个 `PlaneWar` 对象即可启动游戏。
在游戏中,我们使用了 `BufferedImage` 来创建游戏界面的画布,并在每次重绘时将画布绘制到窗口中。我们还使用了 `Rectangle` 类来表示游戏中的物体,并使用 `intersects()` 方法来检测是否有重叠。
阅读全文