ADD file via upload

main
ppx98yace 4 months ago
parent 1d43459cb2
commit 1b55d99e97

@ -0,0 +1,53 @@
package com.snakegame;
import java.awt.*;
import java.util.Random;
public class Food {
private Point position;
private final GameConfig config;
private final Random random = new Random();
private boolean isBigFood;
private long lastBlinkTime;
private boolean isVisible = true;
public Food(GameConfig config) {
this.config = config;
this.respawn();
this.lastBlinkTime = System.currentTimeMillis();
}
public void respawn() {
do {
this.position = new Point(this.random.nextInt(this.config.getWidth()), this.random.nextInt(this.config.getHeight()));
} while(this.position.x < 1 || this.position.y < 1);
this.isBigFood = this.random.nextInt(10) == 0;
}
public void draw(Graphics g, int tileSize) {
long currentTime = System.currentTimeMillis();
if (currentTime - this.lastBlinkTime > 1000L) { // 每秒闪烁一次
this.isVisible = !this.isVisible;
this.lastBlinkTime = currentTime;
}
if (this.isVisible) {
if (this.isBigFood) {
g.setColor(Color.YELLOW);
g.fillOval(this.position.x * tileSize, this.position.y * tileSize, tileSize, tileSize);
} else {
g.setColor(this.config.getFoodColor());
g.fillOval(this.position.x * tileSize, this.position.y * tileSize, tileSize - 2, tileSize - 2);
}
}
}
public Point getPosition() {
return this.position;
}
public boolean isBigFood() {
return this.isBigFood;
}
}
Loading…
Cancel
Save