Conversation
pages/index.js
Outdated
|
|
||
| return () => clearInterval(timer); | ||
| }, [direction, food]); | ||
| }, [direction, foods]); |
There was a problem hiding this comment.
foods state isn't used anywhere inside the useEffect so we can remove it.
pages/index.js
Outdated
| if(direction!==Direction.Left) | ||
| return Direction.Right; | ||
| return direction; | ||
| }) |
There was a problem hiding this comment.
these 4 cases almost do the same thing and we can create a function that calculates the next direction based on the previous direction and the ArrowDirection.
Corei13
left a comment
There was a problem hiding this comment.
I will recommend using VS Code editor and installing prettier to make sure your code are formatted.
Everything else looks great!
pages/index.js
Outdated
| }, [snake]); | ||
| setFoods(currentFoods => [...currentFoods,newFood]); | ||
| setTimeout(() => { | ||
| setFoods((f) => f.filter(e => e.x !=newFood.x && e.y !=newFood.y)) |
There was a problem hiding this comment.
@Corei13 is this a good approach? registering a timeout while creating to execute a removal after 10 seconds
There was a problem hiding this comment.
@owishiboo think of this,
on 11th second you registered a timeout to remove a food on 21th second on a coordinate.
the snake eats the food within 14th second and another food appears on the exact coordinate that should get deleted on 24th second.
but the later food will get deleted on 21th second because the timeout clears that coordinate, it doesn't care about which food. right?
There was a problem hiding this comment.
@royantar0311 I'm so sorry I didn't think of this. I thought the code was working fine.
How can I solve it? I'm really out of ideas.
There was a problem hiding this comment.
one idea is to assign an unique id to each of the foods, and then remove the food by id inside setInterval callback
another is to keep the created time with the food and each second keep only foods that were created within last 10s
pages/index.js
Outdated
| setFoods((f) => | ||
| f.filter( | ||
| (e) => | ||
| e.start!==newFood.start |
There was a problem hiding this comment.
@royantar0311 I've attached an id for each food and now removing food after 10s by using the id. But the game keeps restarting. How can I fix it?
No description provided.