From 01526b8cd8042b4e429060ef3c1120a4f4fbb360 Mon Sep 17 00:00:00 2001 From: Andre Padez Date: Thu, 30 Oct 2025 23:02:26 +0000 Subject: [PATCH] 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 --- src/useGameStatus/useGameStatus.ts | 49 ++++++++++++++++-------------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/src/useGameStatus/useGameStatus.ts b/src/useGameStatus/useGameStatus.ts index 65c983a..c90343e 100755 --- a/src/useGameStatus/useGameStatus.ts +++ b/src/useGameStatus/useGameStatus.ts @@ -82,32 +82,35 @@ export function useGameStatus( return; } - const head = snakeManagerRef.current.snakeBodyRef.current[0]; - if (head && foodManagerRef.current.checkFoodCollision(head)) { - foodManagerRef.current.removeFood(head); - shouldGrow = true; + const head = snakeManagerRef.current.snakeBodyRef.current[0]; + if (head && foodManagerRef.current.checkFoodCollision(head)) { + foodManagerRef.current.removeFood(head); + 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) => { - // 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; - } + foodsEatenRef.current += 1; - foodManagerRef.current.spawnFood( - snakeManagerRef.current.snakeBodyRef.current, - 1 - ); - return newScore; - }); + setScore((prev) => { + // Add points at CURRENT level + let newScore = prev + levelRef.current; + + // 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; + }); }