爆气球小游戏java
时间: 2023-07-09 13:10:32 浏览: 42
好的,我可以为你提供一个简单的爆气球小游戏的 Java 代码:
```java
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class BalloonGame extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private Timer timer;
private int delay = 10;
private int score = 0;
private JLabel scoreLabel;
private JButton startButton;
private JPanel gamePanel;
private Random rand = new Random();
public BalloonGame() {
super("Balloon Game");
JPanel controlsPanel = new JPanel();
controlsPanel.setLayout(new GridLayout(1, 2));
startButton = new JButton("Start");
startButton.addActionListener(this);
controlsPanel.add(startButton);
scoreLabel = new JLabel("Score: " + score);
controlsPanel.add(scoreLabel);
add(controlsPanel, BorderLayout.NORTH);
gamePanel = new JPanel() {
private static final long serialVersionUID = 1L;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < 10; i++) {
int x = rand.nextInt(getWidth() - 40);
int y = rand.nextInt(getHeight() - 40);
g.setColor(new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256)));
g.fillOval(x, y, 40, 40);
}
}
};
add(gamePanel, BorderLayout.CENTER);
timer = new Timer(delay, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
gamePanel.repaint();
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == startButton) {
if (!timer.isRunning()) {
score = 0;
scoreLabel.setText("Score: " + score);
timer.start();
}
}
}
public static void main(String[] args) {
BalloonGame game = new BalloonGame();
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.setSize(400, 400);
game.setVisible(true);
}
}
```
这个游戏的规则很简单:屏幕上会随机出现一些气球,你需要点击它们,每爆一个气球就会得到一分,游戏时间为 10 秒。