fix(phase1.4): check level-up threshold BEFORE incrementing food counter

- Calculate willLevelUp BEFORE foodsEatenRef.current += 1
- This way the 2nd food that triggers level up is still worth 1 point
- Only AFTER eating it do we level up to 2
- Correct: eat food1(+1)=1pt, eat food2(+1, then lvlup)=2pts, eat food3(+2)=4pts
- Issue was checking >= threshold AFTER incrementing, causing wrong level calculation
This commit is contained in:
2025-10-30 23:02:26 +00:00
parent e5b18b814f
commit 01526b8cd8
+26 -23
View File
@@ -82,32 +82,35 @@ export function useGameStatus(
return; return;
} }
const head = snakeManagerRef.current.snakeBodyRef.current[0]; const head = snakeManagerRef.current.snakeBodyRef.current[0];
if (head && foodManagerRef.current.checkFoodCollision(head)) { if (head && foodManagerRef.current.checkFoodCollision(head)) {
foodManagerRef.current.removeFood(head); foodManagerRef.current.removeFood(head);
shouldGrow = true; shouldGrow = true;
foodsEatenRef.current += 1; // Check BEFORE incrementing if we're about to level up
const willLevelUp = (foodsEatenRef.current + 1) >= FOODS_PER_LEVEL;
setScore((prev) => { foodsEatenRef.current += 1;
// Add points at CURRENT level first
let newScore = prev + levelRef.current;
// THEN check if we should level up for NEXT food
if (foodsEatenRef.current >= FOODS_PER_LEVEL) {
const newLevel = levelRef.current + 1;
levelRef.current = newLevel;
setLevel(newLevel);
currentFpsRef.current = INITIAL_FPS + (newLevel - 1);
foodsEatenRef.current = 0;
}
foodManagerRef.current.spawnFood( setScore((prev) => {
snakeManagerRef.current.snakeBodyRef.current, // Add points at CURRENT level
1 let newScore = prev + levelRef.current;
);
return newScore; // Level up AFTER this food if threshold was reached
}); if (willLevelUp) {
const newLevel = levelRef.current + 1;
levelRef.current = newLevel;
setLevel(newLevel);
currentFpsRef.current = INITIAL_FPS + (newLevel - 1);
foodsEatenRef.current = 0;
}
foodManagerRef.current.spawnFood(
snakeManagerRef.current.snakeBodyRef.current,
1
);
return newScore;
});
} }