切水果java小游戏代码
时间: 2024-12-21 19:11:04 浏览: 12
切水果Java小游戏的代码通常涉及到基本的游戏循环、用户输入处理、碰撞检测以及图形绘制。这里给出一个简单的示例,假设我们有一个Flappy Fruit游戏:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class FruitSlicer extends JFrame {
private static final int FRUIT_WIDTH = 50;
private static final int FRUIT_HEIGHT = 50;
private static final int INTERVAL_MS = 100; // 每隔多少毫秒移动一次水果
private JButton sliceButton;
private Fruit fruit;
public FruitSlicer() {
initGame();
setSize(FRUIT_WIDTH * 4 + 100, FRUIT_HEIGHT * 2);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void initGame() {
sliceButton = new JButton("切水果");
add(sliceButton, BorderLayout.NORTH);
sliceButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (fruit != null) {
// 在这里添加切水果的逻辑,比如改变游戏状态或得分
System.out.println("切到了水果!");
}
}
});
fruit = new Fruit(100, FRUIT_HEIGHT / 2); // 创建初始水果的位置
}
class Fruit extends JPanel implements Runnable {
private int x;
public Fruit(int startX, int startY) {
x = startX;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(x, startY, FRUIT_WIDTH, FRUIT_HEIGHT);
}
@Override
public void run() {
while (true) {
setLocation(x++, 0);
try {
Thread.sleep(INTERVAL_MS);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
if (x > getWidth()) { // 当水果超出屏幕时,开始新的水果
x = 0;
fruit = new Fruit(x, FRUIT_HEIGHT / 2);
}
}
}
}
public static void main(String[] args) {
new FruitSlicer();
}
}
阅读全文