From 1b55d99e97fc9a46d3e3d03cb7dc9160c3ee6325 Mon Sep 17 00:00:00 2001 From: ppx98yace <3576677045@qq.com> Date: Sat, 29 Mar 2025 23:21:38 +0800 Subject: [PATCH] ADD file via upload --- src/Food.java | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/Food.java diff --git a/src/Food.java b/src/Food.java new file mode 100644 index 0000000..f909bce --- /dev/null +++ b/src/Food.java @@ -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; + } +} \ No newline at end of file