:java400行能干啥?不如写个飞翔小鸟游戏吧_asbbv的博客-CSDN博客
时间: 2023-10-17 13:27:10 浏览: 98
Java 400行的代码可以实现许多不同的功能,具体取决于你想要实现什么样的功能。关于写一个飞翔小鸟游戏的想法,这是个很有趣的项目!下面是一个简单的示例代码,用于实现一个基本的飞翔小鸟游戏:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class FlappyBirdGame extends JFrame {
private static final int WIDTH = 400;
private static final int HEIGHT = 600;
private int birdY;
private int birdVelocity;
public FlappyBirdGame() {
setTitle("Flappy Bird");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
birdY = HEIGHT / 2;
birdVelocity = 0;
addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
birdVelocity = -10;
}
}
});
Thread gameThread = new Thread(() -> {
while (true) {
birdVelocity += 1;
birdY += birdVelocity;
if (birdY >= HEIGHT - 30) { // 鸟碰到地板,游戏结束
JOptionPane.showMessageDialog(null, "Game Over!");
System.exit(0);
}
repaint();
try {
Thread.sleep(20);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
});
gameThread.start();
}
public void paint(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.RED);
g.fillOval(WIDTH / 2 - 10, birdY - 10, 20, 20);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
FlappyBirdGame game = new FlappyBirdGame();
game.setVisible(true);
});
}
}
```
这只是一个简单的示例,你可以根据自己的需求进行扩展和修改。希望对你有帮助!
阅读全文