Reputation: 87
Context : I'm making a version of the popular game, Snake. And I encounter some issues when I try to avoid the appearance of the food at the same place of the parts of my snake.
So I produced this code with the framework Phaser :
generateFood: function() {
var randomX, randomY;
var rightLocation = false;
var foodOnSnake = false;
while(rightLocation === false) {
randomX = Math.floor(Math.random() * (this.game.width / squareSize)) * squareSize;
randomY = Math.floor(Math.random() * (this.game.height / squareSize)) * squareSize;
foodOnSnake = false;
for (var i = 0; i < snake.length; i++) {
if (snake[i].x === food.x && snake[i].y === food.y) {
foodOnSnake = true;
break;
}
}
if(foodOnSnake === false) {
rightLocation = true;
}
}
food = this.game.add.sprite(randomX, randomY, 'snake', 15);
}
The aim, is to create some random coordinates on the game. And, while the food is generate on a part of the snake (the for loop), I will generate other coordinates. But for unknown reason, after my snake is eaten the first food, the game crashed and the tab of Google Chrome does not responding. I think there is a mistake with a loop but I can't find it.
Upvotes: 0
Views: 173
Reputation: 42520
You compare the coordinates of the snake's segments with food.x
and food.y
, which you never update inside the loop:
if (snake[i].x === food.x && snake[i].y === food.y) {
I believe you want to compare it to randomX
and randomY
instead:
if (snake[i].x === randomX && snake[i].y === randomY) {
Depending on the value of food
's coordinates, your function likely results in an infinite loop.
Upvotes: 4