0
votes

I am attempting to smooth out the animation of the snake in my snake game app. It is currently on a 30x30 pixel grid. Canvas is 600x600. When I change the increment labeled pixel to a number I feel works in my direction function.

It throws the 30x30 grid off and moves along the new integer implemented. Thus causing the apple to not get eaten when moving over it.

//sets the starting pixel for the snake & food
let pixel = 30;
 //moves snake according to which direction the user initiates
    if (snakeDirection == "LEFT") snakeX -= pixel;
    if (snakeDirection == "UP") snakeY -= pixel;
    if (snakeDirection == "RIGHT") snakeX += pixel;
    if (snakeDirection == "DOWN") snakeY += pixel;

And when it is changed to this:

//moves snake according to which direction the user initiates
    if (snakeDirection == "LEFT") snakeX -= 5;
    if (snakeDirection == "UP") snakeY -= 5;
    if (snakeDirection == "RIGHT") snakeX += 5;
    if (snakeDirection == "DOWN") snakeY += 5;

It causes the snake to move to my desired rate but throws it off the grid.

I am drawing my snake calling the array in a for loop to increment in size:

//draws snake
    for (let i = 0; i < snake.length; i++) {
        ctx.fillStyle = (i == 0) ? "red" : "white";
        ctx.fillRect(snake[i].x, snake[i].y +4.66, pixel, pixel);

        ctx.strokeStyle = (i ==0) ? "white" : "black";
        ctx.strokeRect(snake[i].x, snake[i].y +4.66, pixel, pixel);
    }

And I have my snake array set like this:

//creates snake array
let snake = [];
snake[0] = {
    x: 15 * pixel,
    y: 16 * pixel
}

Here is my GitHub link https://github.com/George-Jindo/js-snake-game

1

1 Answers

0
votes

The way I would deal with this is to add some tolerance to the part of your code where you determine whether the snake is touching the apple.

If you change line 81 to:

if (Math.abs(snakeX - apple.x) < pixel && Math.abs(snakeY - apple.y) < pixel) {

Then the apple will be collected if the snake is within "pixel" of the apple.

Another approach would be to only allow the user to change the direction the snake was moving when they were exactly over a block. That would be a little more difficult to implement.