用Java写一个切水果小游戏
时间: 2023-09-15 18:17:26 浏览: 332
好的,那我来给您提供一个简单的切水果小游戏的Java代码实现。
首先,我们需要导入Java的图形化界面库`javax.swing`以及其他必要的库:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
```
然后,我们需要定义一些全局变量,包括游戏窗口的大小、水果的数量和速度、得分等信息:
```java
public class FruitNinja extends JFrame implements ActionListener {
private final int WINDOW_WIDTH = 600;
private final int WINDOW_HEIGHT = 600;
private final int FRUIT_COUNT = 6;
private final int FRUIT_SPEED = 10;
private int score = 0;
private JLabel scoreLabel;
private Timer timer;
private Random random;
private final String[] FRUIT_NAMES = {"apple", "banana", "grape", "kiwi", "orange", "pear"};
private JLabel[] fruitLabels = new JLabel[FRUIT_COUNT];
}
```
接下来,我们需要在`FruitNinja`类的构造函数中初始化游戏窗口、设置游戏得分标签等信息:
```java
public FruitNinja() {
setTitle("Fruit Ninja");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
setBackground(Color.BLACK);
scoreLabel = new JLabel("Score: " + score);
scoreLabel.setForeground(Color.WHITE);
scoreLabel.setBounds(10, 10, 100, 20);
add(scoreLabel);
random = new Random();
timer = new Timer(1000 / FRUIT_SPEED, this);
timer.start();
setVisible(true);
}
```
然后,我们需要实现`actionPerformed`方法,用于处理游戏逻辑:
```java
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < FRUIT_COUNT; i++) {
if (fruitLabels[i] == null) {
int x = random.nextInt(WINDOW_WIDTH - 50);
int y = WINDOW_HEIGHT;
int index = random.nextInt(FRUIT_NAMES.length);
fruitLabels[i] = new JLabel(new ImageIcon(FRUIT_NAMES[index] + ".png"));
fruitLabels[i].setBounds(x, y, 50, 50);
add(fruitLabels[i]);
} else {
fruitLabels[i].setLocation(fruitLabels[i].getX(), fruitLabels[i].getY() - 10);
if (fruitLabels[i].getY() < -50) {
remove(fruitLabels[i]);
fruitLabels[i] = null;
}
}
}
scoreLabel.setText("Score: " + score);
}
```
最后,我们需要在`main`方法中创建一个`FruitNinja`对象,即可启动游戏:
```java
public static void main(String[] args) {
new FruitNinja();
}
```
完整的代码实现如下所示:
阅读全文