bob
bob

Reputation: 9

Snake game bug issue

I have a snake game but sometimes the food is placed where the snake is at the moment. I have created this code as I thought it woyld work, it runs fine but does not change anything?

function CreateFood() {
    food = {
        x: Math.round(Math.random()*(w-cellSize)/cellSize),
        y: Math.round(Math.random()*(h-cellSize)/cellSize),
    };

    for(var i = 0; i < snakeArray.length; i++) {
        if (snakeArray[i].x == food.x && snakeArray[i].y == food.y) {
            CreateFood();
        }  
    }
}

EDIT: Some methods use this like paintfoodcells method etc, and I have a paint snakecells method. What I am trying to do is if the random food location that gets generated is the same as one of the snakearrays location then it just tries again. For the whole source code go to the link provided and right click view source. http://www.taffatech.com/Snake.html

Upvotes: 0

Views: 257

Answers (1)

Simon
Simon

Reputation: 6363

I think the problem is that you are using recursion. When you detect that the food has the same position as the snake you create a new food object but you don't change the value of the first one. Instead try a while loop.

done = true;
while (done == false){
    food = {
    x: Math.round(Math.random()*(w-cellSize)/cellSize),
    y: Math.round(Math.random()*(h-cellSize)/cellSize),
};

for(var i = 0; i < snakeArray.length; i++) {
    if (snakeArray[i].x == food.x && snakeArray[i].y == food.y) {
        done = false;
    }  
}

}

Upvotes: 1

Related Questions