I'm implementing a Snake game in javascript for fun, I have successfully implemented the snake, its movements and the snake-growth thing as it eats an apple.
To calculate the apple position I'm currently following these steps:
Unfortunately I found out that this algorithm is very weak.. let's say I have a 10 x 10 game container, the red square is the apple, the green square is my snake head (initial game state)
as the game progresses the snake eats more and more apples, increasing its length and leaving less and less empty cells to place an apple
Now suppose that the snake reaches a length equals to 99 while eating an apple. This means that there's only one square left to place the next apple. My algorithm (this is the worst case obviously) could take forever in order to randomize the correct value, as it discards any randomized position that it's already taken by the snake's head or tail, not caring at all to randomize the new position in a range of "empty cells" only but instead randomizing on the whole 10 x 10 game canvas.
How should I proceed to solve my busillis? Can you give me any advice on a good algorithm that I can use?
Thank you
As said in comments, the easiest solution I can think is to make a list of free coordinates and then just choose randomly from them. And you can calculate free coordinates only if needed(when you need to add an apple).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With