用Java语言写一个飞机大战游戏
时间: 2023-11-22 09:51:47 浏览: 62
好的,以下是一个简单的飞机大战游戏的Java代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PlaneGame extends JFrame implements ActionListener, KeyListener {
private int x, y, bx, by;
private ImageIcon planeIcon, bulletIcon, bgIcon;
private Timer timer;
private boolean left, right, up, down, fire;
public PlaneGame() {
setTitle("Plane Game");
setSize(500, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
setLayout(null);
x = 220;
y = 500;
bx = x + 25;
by = y - 25;
planeIcon = new ImageIcon("plane.png");
bulletIcon = new ImageIcon("bullet.png");
bgIcon = new ImageIcon("bg.jpg");
timer = new Timer(10, this);
timer.start();
addKeyListener(this);
}
public void paint(Graphics g) {
super.paint(g);
g.drawImage(bgIcon.getImage(), 0, 0, null);
g.drawImage(planeIcon.getImage(), x, y, null);
if (fire) {
g.drawImage(bulletIcon.getImage(), bx, by, null);
by -= 5;
if (by < 0) {
fire = false;
bx = x + 25;
by = y - 25;
}
}
}
public void actionPerformed(ActionEvent e) {
if (left) x -= 5;
if (right) x += 5;
if (up) y -= 5;
if (down) y += 5;
if (x < 0) x = 0;
if (x > 450) x = 450;
if (y < 30) y = 30;
if (y > 500) y = 500;
repaint();
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_LEFT) left = true;
if (code == KeyEvent.VK_RIGHT) right = true;
if (code == KeyEvent.VK_UP) up = true;
if (code == KeyEvent.VK_DOWN) down = true;
if (code == KeyEvent.VK_SPACE) fire = true;
}
public void keyReleased(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_LEFT) left = false;
if (code == KeyEvent.VK_RIGHT) right = false;
if (code == KeyEvent.VK_UP) up = false;
if (code == KeyEvent.VK_DOWN) down = false;
}
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
new PlaneGame();
}
}
```
这个游戏只有一个玩家控制一个飞机,并且可以发射子弹。如果需要更加复杂的游戏玩法,需要进一步完善代码。
阅读全文