用java手写FlyBird
时间: 2024-03-23 07:41:07 浏览: 13
好的,我可以为您提供一个简单的Java程序来手写FlyBird游戏。以下是代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FlyBird extends JPanel implements ActionListener, KeyListener {
private Timer timer;
private int birdX, birdY, velocity;
private boolean gameOver;
private int[] pipeX, pipeY, pipeHeight, pipeGap;
private int score;
public FlyBird() {
setBackground(Color.WHITE);
setPreferredSize(new Dimension(600, 400));
setFocusable(true);
addKeyListener(this);
birdX = 100;
birdY = 200;
velocity = 0;
gameOver = false;
pipeX = new int[3];
pipeY = new int[3];
pipeHeight = new int[3];
pipeGap = new int[3];
score = 0;
for (int i = 0; i < 3; i++) {
pipeX[i] = 400 + i * 200;
pipeY[i] = (int) (Math.random() * 200) + 50;
pipeHeight[i] = (int) (Math.random() * 150) + 50;
pipeGap[i] = 100;
}
timer = new Timer(30, this);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
for (int i = 0; i < 3; i++) {
g.fillRect(pipeX[i], 0, 50, pipeY[i]);
g.fillRect(pipeX[i], pipeY[i] + pipeGap[i], 50, getHeight() - pipeY[i] - pipeGap[i]);
}
g.setColor(Color.RED);
g.fillRect(birdX, birdY, 20, 20);
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.BOLD, 20));
g.drawString("Score: " + score, 10, 30);
if (gameOver) {
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.BOLD, 40));
g.drawString("Game Over!", getWidth() / 2 - 100, getHeight() / 2 - 20);
}
}
public void actionPerformed(ActionEvent e) {
if (!gameOver) {
birdY += velocity;
velocity += 2;
for (int i = 0; i < 3; i++) {
pipeX[i] -= 5;
if (pipeX[i] < -50) {
pipeX[i] = 600;
pipeY[i] = (int) (Math.random() * 200) + 50;
pipeHeight[i] = (int) (Math.random() * 150) + 50;
score++;
}
if (birdX + 20 > pipeX[i] && birdX < pipeX[i] + 50) {
if (birdY < pipeY[i] || birdY + 20 > pipeY[i] + pipeGap[i]) {
gameOver = true;
}
}
}
if (birdY > getHeight()) {
gameOver = true;
}
repaint();
}
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
velocity = -20;
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
JFrame frame = new JFrame("Fly Bird");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new FlyBird());
frame.pack();
frame.setVisible(true);
}
}
```
这段代码实现了一个基本的Flappy Bird游戏。您可以在JFrame中运行它,并通过按空格键来控制小鸟的上升。在游戏中,您需要通过一些管道来得分,但是如果碰到了管道或者掉落到画面下方,游戏就结束了。