java代码实现fly bird游戏源代码

以下是一个简单的Java代码实现飞行鸟游戏:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class FlyBird extends JFrame implements ActionListener, KeyListener {
    private JPanel panel;
    private JLabel bird;
    private int birdX, birdY, score;
    private Timer timer;
    private boolean gameOn;

    public FlyBird() {
        setTitle("Fly Bird");
        setSize(400, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        panel = new JPanel();
        panel.setLayout(null);

        bird = new JLabel(new ImageIcon("bird.png"));
        bird.setSize(50, 50);
        bird.setLocation(50, 200);
        panel.add(bird);

        birdX = bird.getX();
        birdY = bird.getY();
        score = 0;

        timer = new Timer(50, this);
        timer.start();

        gameOn = true;

        addKeyListener(this);

        setContentPane(panel);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        if (gameOn) {
            birdY -= 5;
            bird.setLocation(birdX, birdY);
            if (bird.getY() < 0)
                gameOver();
        }
    }

    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_SPACE) {
            birdY += 50;
            bird.setLocation(birdX, birdY);
            score++;
        }
    }

    public void keyTyped(KeyEvent e) {}
    public void keyReleased(KeyEvent e) {}

    private void gameOver() {
        gameOn = false;
        JOptionPane.showMessageDialog(this, "Game Over!\nScore: " + score);
    }

    public static void main(String[] args) {
        new FlyBird();
    }
}

在这个例子中,我们创建了一个JFrame窗口,它包含一个JPanel,上面放置了一个图像标签表示小鸟。我们使用一个计时器,以每50毫秒的速度移动小鸟。

 
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:
确定