Skip to content
Advertisement

browser freezing when in while loop (snake game)

I’m making the popular snake game for js homework. I have a function which is meant to ensure that after an apple is eaten it moves to a different location on the canvas while not being on any part of the snake, the function without the loop works fine (though apples are placed on the snake too):

JavaScript

the function though with the loop ends up freezing after a few apples are eaten (right before hitting an apple):

JavaScript

with getRandomNumber being:

JavaScript

this is my second question on SO, don’t fry me please….

Advertisement

Answer

I didn’t get a moment to test but I suspect it’s as simple as the following evalutation.

JavaScript

You are accepting either X or Y collision. Meaning the apple cannot share any X or Y coordinates with any of the snake pieces. What you want instead is and I believe. It’s like saying we both live on the same house because we live on the same street. No, we need to also have the same address.

As a safety, you could add a limit to how many iterations of the loop can run in the event their is no more space remaining for an apple.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement