Conversation
| useEffect(() => { | ||
| const updateFood = () => { | ||
| setFood((food) => { | ||
| const foodCell = getRandomCell(); |
There was a problem hiding this comment.
a random cell can be a food or a snake cell already, we should check if it is not and only allow a cell that isn't already a snake/food.
condition should look like this: isFood(foodCell) || isSnake(foodCell)
| newHead.y = 0; | ||
| else if (newHead.x < 0) | ||
| newHead.x = 24; | ||
| else if (newHead.x > 24) |
There was a problem hiding this comment.
this checking works but a better approach would have been using mod operation on the newHeads coordinates so they always lie between 0 - 24
like this x = (head.x + direction.x) % Config.width
but this calculation can produce a bug, can you find out ?
| setSnake(() => getDefaultSnake()); | ||
| setDirection(() => Direction.Right); | ||
| setFood([{ x: 4, y: 10, createdAt: Date.now() }]); | ||
| setScore(() => 0); |
There was a problem hiding this comment.
when using a setState, if you need the previous value of the state, you can use a function like this
setState((previousValue) => returnCalculatedNewValue)
but if the new value is independant of the previous one, you can simply set it
setState(independantNewValue)
| setDirection(Direction.Right); | ||
| case "ArrowDown": | ||
|
|
||
| setDirection((prevDirection) => { |
There was a problem hiding this comment.
by creating a helper function that takes in the directions and calculates the next direction, you can remove the redundancy
I have completed the tasks but the code is very messy :')