用java写一个飞机大战
时间: 2023-12-31 12:04:46 浏览: 132
好的,以下是一个简单的飞机大战游戏的 Java 代码示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PlaneWar extends JFrame {
private MyPanel myPanel = null;
public static void main(String[] args) {
new PlaneWar();
}
public PlaneWar() {
myPanel = new MyPanel();
this.add(myPanel);
this.setSize(400, 600);
this.setTitle("PlaneWar");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
class MyPanel extends JPanel {
private ImageIcon background = new ImageIcon("background.jpg");
private ImageIcon planeIcon = new ImageIcon("plane.png");
private ImageIcon bulletIcon = new ImageIcon("bullet.png");
private int planeX = 175, planeY = 500;
private int bulletX = planeX + 30, bulletY = planeY - 20;
private boolean isFiring = false;
public void paint(Graphics g) {
super.paint(g);
// 绘制背景
g.drawImage(background.getImage(), 0, 0, null);
// 绘制玩家飞机
g.drawImage(planeIcon.getImage(), planeX, planeY, null);
// 绘制子弹
if (isFiring) {
g.drawImage(bulletIcon.getImage(), bulletX, bulletY, null);
}
}
public MyPanel() {
// 添加键盘监听器
this.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
switch (code) {
case KeyEvent.VK_LEFT:
if (planeX > 0) planeX -= 10;
break;
case KeyEvent.VK_RIGHT:
if (planeX < 340) planeX += 10;
break;
case KeyEvent.VK_SPACE:
if (!isFiring) {
isFiring = true;
bulletX = planeX + 30;
bulletY = planeY - 20;
// 开始子弹线程
new BulletThread().start();
}
break;
}
repaint();
}
});
// 设置焦点
this.setFocusable(true);
}
class BulletThread extends Thread {
public void run() {
while (isFiring) {
bulletY -= 10;
if (bulletY < -bulletIcon.getIconHeight()) {
isFiring = false;
break;
}
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
repaint();
}
}
}
}
}
```
这个游戏非常简单,只有一个玩家飞机和子弹。玩家可以使用左右箭头控制飞机移动,使用空格键开火。子弹线程会不断更新子弹的位置,当子弹飞出屏幕时,线程会结束。
阅读全文