Conversation
|
Mahdi ( ! Mehdi ) understood |
pages/index.js
Outdated
| setFood(newFood); | ||
| // remove the eaten food | ||
| setFoods((fs) => fs.filter((f) => f.x !== head.x && f.y !== head.y)); | ||
| addNewFood(); |
There was a problem hiding this comment.
the requirement was to add food every 3 secs. do we still need to add a new one after the snake eats a food?
pages/index.js
Outdated
| //removing oldest food after 10 seconds | ||
| useEffect(() => { | ||
| const interval = setInterval(() => { | ||
| removeFood(); |
There was a problem hiding this comment.
if you are removing a food every 10 secs, how do you make sure every of them stays on the grid for exactly 10s?
1st food appears on 0s
2nd food appears on 3s
3rd food appears on 6s...
1st food gets removed on 10s
2nd food gets removed on 20s -> but shouldn't it get removed on 13s?
There was a problem hiding this comment.
//removing oldest food after 10 seconds
let i = 0;
useEffect(() => {
const interval = setInterval(() => {
i++;
removeFood();
}, i * 3000 + 10000);
return () => clearInterval(interval);
}, [i]);Is it the solution?
There was a problem hiding this comment.
put a log before the removeFood() function call and see when is the interval callBack getting called
|
|
||
| const [food, setFood] = useState({ x: 4, y: 10 }); | ||
| const [score, setScore] = useState(0); | ||
| const [foods, setFoods] = useState([{ x: 4, y: 10 }]); |
There was a problem hiding this comment.
hint: in addition to x and y, you can add another field like time, and use that to store when the food was created (with Date.now()). Then you can use that time determine if a food was created >10s ago and remove them.
No description provided.