java彩虹雨小游戏代码
时间: 2023-07-02 22:15:48 浏览: 213
以下是一个简单的 Java 彩虹雨小游戏代码示例:
```java
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class RainbowGame extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 400;
private static final int HEIGHT = 400;
private static final int DELAY = 50;
private static final int FONT_SIZE = 30;
private static final String[] COLORS = {"red", "orange", "yellow", "green", "blue", "indigo", "violet"};
private static final Random rand = new Random();
private Timer timer;
private JLabel textLabel;
private Color currentColor;
public RainbowGame() {
super("Rainbow Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(WIDTH, HEIGHT);
setResizable(false);
setLocationRelativeTo(null);
setLayout(new BorderLayout());
textLabel = new JLabel("Press the space bar to start.", JLabel.CENTER);
textLabel.setFont(new Font("Arial", Font.BOLD, FONT_SIZE));
add(textLabel, BorderLayout.CENTER);
timer = new Timer(DELAY, this);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == timer) {
currentColor = getRandomColor();
textLabel.setForeground(currentColor);
}
}
private Color getRandomColor() {
int index = rand.nextInt(COLORS.length);
switch (COLORS[index]) {
case "red":
return Color.RED;
case "orange":
return Color.ORANGE;
case "yellow":
return Color.YELLOW;
case "green":
return Color.GREEN;
case "blue":
return Color.BLUE;
case "indigo":
return new Color(75, 0, 130); // dark blue
case "violet":
return new Color(148, 0, 211); // dark violet
default:
return Color.BLACK;
}
}
private void startGame() {
textLabel.setText("Rainbow Game!");
textLabel.setForeground(Color.BLACK);
timer.start();
}
private void endGame() {
timer.stop();
textLabel.setText("Game over.");
textLabel.setForeground(Color.BLACK);
}
public static void main(String[] args) {
RainbowGame game = new RainbowGame();
game.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
if (game.timer.isRunning()) {
game.endGame();
} else {
game.startGame();
}
}
}
});
}
}
```
这个小游戏的规则很简单:按下空格键开始游戏,每隔一段时间,文字颜色会随机变化,直到用户再次按下空格键结束游戏。
阅读全文