写一个飞机大战的Java代码
时间: 2024-04-08 17:30:49 浏览: 144
飞机大战源代码(Java版本).zip
5星 · 资源好评率100%
以下是一个简单的飞机大战的Java代码示例:
```java
import java.awt.*;
import java.awt.event.*;
public class PlaneGame extends Frame {
private Plane plane = new Plane(250, 250); // 创建飞机对象
private Image offScreenImage = null; // 双缓冲技术相关
private Graphics gOffScreen = null; // 双缓冲技术相关
public void launchFrame() {
setSize(500, 500);
setLocation(100, 100);
setVisible(true);
// 添加键盘监听器,控制飞机移动
addKeyListener(new KeyMonitor());
// 使用线程不断重画窗口
new Thread(new PaintThread()).start();
}
public void paint(Graphics g) {
// 绘制背景
Color c = g.getColor();
g.setColor(Color.GRAY);
g.fillRect(0, 0, 500, 500);
g.setColor(c);
// 绘制飞机
plane.draw(g);
}
public void update(Graphics g) {
if (offScreenImage == null) {
offScreenImage = this.createImage(500, 500);
gOffScreen = offScreenImage.getGraphics();
}
paint(gOffScreen);
g.drawImage(offScreenImage, 0, 0, null);
}
public static void main(String[] args) {
new PlaneGame().launchFrame();
}
private class PaintThread implements Runnable {
public void run() {
while (true) {
repaint(); // 重画窗口
try {
Thread.sleep(40); // 休眠40ms,约每秒25帧
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private class KeyMonitor extends KeyAdapter {
public void keyPressed(KeyEvent e) {
plane.addDirection(e);
}
public void keyReleased(KeyEvent e) {
plane.minusDirection(e);
}
}
private class Plane {
private int x, y; // 飞机的坐标
private boolean left, right, up, down; // 飞机的移动方向
public Plane(int x, int y) {
this.x = x;
this.y = y;
}
public void draw(Graphics g) {
Color c = g.getColor();
g.setColor(Color.YELLOW);
g.fillOval(x, y, 10, 10);
g.setColor(c);
move();
}
public void move() {
if (left) {
x -= 3;
}
if (right) {
x += 3;
}
if (up) {
y -= 3;
}
if (down) {
y += 3;
}
}
public void addDirection(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
left = true;
break;
case KeyEvent.VK_RIGHT:
right = true;
break;
case KeyEvent.VK_UP:
up = true;
break;
case KeyEvent.VK_DOWN:
down = true;
break;
}
}
public void minusDirection(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
left = false;
break;
case KeyEvent.VK_RIGHT:
right = false;
break;
case KeyEvent.VK_UP:
up = false;
break;
case KeyEvent.VK_DOWN:
down = false;
break;
}
}
}
}
```
这个代码创建了一个简单的窗口,其中包含一个飞机对象和键盘监听器来控制飞机的移动。每40毫秒重画窗口,使飞机看起来移动起来。运行该代码,你可以使用键盘的方向键来控制飞机的移动。请注意,这只是一个简单的示例,你可以根据需求进行扩展和修改。
阅读全文