Skip to content

Module #1 ( ! Mehdi)#14

Open
MahdiMurshed wants to merge 3 commits intorecruit-org:module-1from
MahdiMurshed:module-1
Open

Module #1 ( ! Mehdi)#14
MahdiMurshed wants to merge 3 commits intorecruit-org:module-1from
MahdiMurshed:module-1

Conversation

@MahdiMurshed
Copy link
Copy Markdown

No description provided.

@royantar0311
Copy link
Copy Markdown

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();
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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();
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Author

@MahdiMurshed MahdiMurshed Mar 14, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  //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?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 }]);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants