爆气球小游戏java
时间: 2023-07-09 21:10:39 浏览: 51
好的,我可以给你提供一个简单的爆气球小游戏的Java代码框架,你可以在此基础上进行开发:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BalloonGame extends JPanel implements ActionListener, MouseListener {
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private static final int MAX_BALLOONS = 20;
private static final int BALLOON_RADIUS = 30;
private static final int BALLOON_SPEED = 5;
private Timer timer;
private Balloon[] balloons;
private int numBalloons;
public BalloonGame() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setBackground(Color.WHITE);
balloons = new Balloon[MAX_BALLOONS];
numBalloons = 0;
timer = new Timer(50, this);
timer.start();
addMouseListener(this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < numBalloons; i++) {
balloons[i].draw(g);
}
}
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < numBalloons; i++) {
balloons[i].move();
}
repaint();
}
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
for (int i = 0; i < numBalloons; i++) {
if (balloons[i].contains(x, y)) {
balloons[i].pop();
return;
}
}
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
private class Balloon {
private int x;
private int y;
private int radius;
private int dx;
private int dy;
private boolean popped;
public Balloon() {
radius = BALLOON_RADIUS;
x = (int) (Math.random() * (WIDTH - 2 * radius)) + radius;
y = (int) (Math.random() * (HEIGHT - 2 * radius)) + radius;
dx = (int) (Math.random() * 2 * BALLOON_SPEED) - BALLOON_SPEED;
dy = (int) (Math.random() * 2 * BALLOON_SPEED) - BALLOON_SPEED;
popped = false;
}
public void draw(Graphics g) {
if (!popped) {
g.setColor(Color.RED);
g.fillOval(x - radius, y - radius, 2 * radius, 2 * radius);
}
}
public void move() {
if (!popped) {
x += dx;
y += dy;
if (x < radius || x > WIDTH - radius) {
dx = -dx;
}
if (y < radius || y > HEIGHT - radius) {
dy = -dy;
}
}
}
public boolean contains(int x, int y) {
return !popped && Math.sqrt((this.x - x) * (this.x - x) + (this.y - y) * (this.y - y)) < radius;
}
public void pop() {
popped = true;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Balloon Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new BalloonGame());
frame.pack();
frame.setVisible(true);
}
}
```
这个代码框架中定义了一个 `BalloonGame` 类,实现了 `ActionListener` 和 `MouseListener` 接口,同时定义了一个 `Balloon` 类,用于表示气球的属性和行为。在 `BalloonGame` 类的构造方法中初始化了气球数组、定时器和鼠标事件监听器,并且在 `paintComponent` 方法中绘制气球。在 `actionPerformed` 方法中更新气球的位置,在 `mouseClicked` 方法中判断鼠标点击的位置是否在气球范围内,并弹掉气球。最后,在 `main` 方法中创建一个 `JFrame` 对象,并将 `BalloonGame` 对象作为其内容面板。你可以根据这个代码框架进行开发,实现你自己的爆气球小游戏。