Problem in Snake game code

Asked

Viewed 52 times

-2

After learning Javascript, I created a challenge for myself: remake the "cobrinha game". However, I have a problem: I want that when the snake goes through the food, the food changes places, but it remains in the same place.

//canvas
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    ctx.fillStyle = "lightgreen";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    //variaveis
    let grid = 20;
    let size = 5;
    let directions = [];
    //cobra
    let head = {
        x: 10,
        y: 10,
    };
    let tail = {
        x: 10,
        y: 10,
    };
    //comida
    let food = {
        x: Math.floor(Math.random() * grid) * grid,
        y: Math.floor(Math.random() * grid) * grid,
    };
    //função principal
    function main(e) {
        switch (e.keyCode) {
            case 37:
                head.x--;
                directions.push('left');
                break;
            case 38:
                head.y--;
                directions.push('up');
                break;
            case 39:
                head.x++;
                directions.push('right');
                break;
            case 40:
                head.y++;
                directions.push('down');
                break;
        };
        ctx.fillStyle = 'red';
        ctx.fillRect(food.x, food.y, grid, grid);
        ctx.fillStyle = 'black';
        ctx.fillRect(head.x * grid, head.y * grid, grid, grid);
        if (directions.length >= size) {        
            ctx.fillStyle = 'lightgreen';
            ctx.fillRect(tail.x * grid, tail.y * grid, grid, grid);
            switch (directions.shift()) {
                case 'left':
                    tail.x--;
                    break;
                case 'up':
                    tail.y--;
                    break;
                case 'right':
                    tail.x++
                    break;
                case 'down':
                    tail.y++;
                    break;
            };
        };
        if (head.x == food.x && head.y == food.y) {
            food.x = Math.floor(Math.random() * grid) * grid;
            food.y = Math.floor(Math.random() * grid) * grid;   
        };
    };
    document.addEventListener('keydown', main);
<!DOCTYPE html>
<html lang="pt-br">
  <head>
    <title>Jogo da cobrinha</title>
    <meta charset="utf-8" />
    <meta name="author" content="Tomás Ricardo" />
  </head>
  <body>
    <canvas id="canvas" width="400" height="400"></canvas>
    
  </body>
</html>

  • Hello Thomas, if you put one console.log(head.x, food.x, head.y, food.y); before IF will notice that the X and Y values of both are totally different. And the problem with this location difference is because of how you added the objects: ctx.fillRect(food.x, food.y, grid, grid); ctx.fillRect(head.x * grid, head.y * grid, grid, grid);

  • Good afternoon, Tomás. Do not add "[Solved]" to the question title. If any answer has solved your problem, just mark the answer as accepted.

1 answer

0


You have made an unnecessary multiplication to the value of food with the grid in:

let food = {
        x: Math.floor(Math.random() * grid) * grid,
        y: Math.floor(Math.random() * grid) * grid,
    };

this makes the values of head.x head.y are always different from food.x and food.y. Remove the second multiply, leave so:

let food = {
        x: Math.floor(Math.random() * grid),
        y: Math.floor(Math.random() * grid),
      };

You forgot to multiply by grid in function ctx.fillRect in :

ctx.fillRect(food.x, food.y, grid, grid);

put it like this:

ctx.fillRect(food.x * grid, food.y * grid, grid, grid);

and there in his if, remove the extra multiplication of grid:

if (head.x == food.x && head.y == food.y) {
          food.x = Math.floor(Math.random() * grid) * grid;
          food.y = Math.floor(Math.random() * grid) * grid;
        }

Stay like this:

if (head.x == food.x && head.y == food.y) {
          food.x = Math.floor(Math.random() * grid);
          food.y = Math.floor(Math.random() * grid);
        }

Now the values of head and food will match at some point and then the position of the food will change(see the console.log()). Follow the full code (run and see the expected result is this):

//canvas
      const canvas = document.getElementById('canvas');
      const ctx = canvas.getContext('2d');
      ctx.fillStyle = 'lightgreen';
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      //variaveis
      let grid = 20;
      let size = 5;
      let directions = [];
      //cobra
      let head = {
        x: 10,
        y: 10,
      };
      let tail = {
        x: 10,
        y: 10,
      };
      //comida
      let food = {
        x: Math.floor(Math.random() * grid),
        y: Math.floor(Math.random() * grid),
      };
      //função principal
      function main(e) {
        switch (e.keyCode) {
          case 37:
            head.x--;
            directions.push('left');
            break;
          case 38:
            head.y--;
            directions.push('up');
            break;
          case 39:
            head.x++;
            directions.push('right');
            break;
          case 40:
            head.y++;
            directions.push('down');
            break;
        }
        ctx.fillStyle = 'red';
        ctx.fillRect(food.x * grid, food.y * grid, grid, grid);
        ctx.fillStyle = 'black';
        ctx.fillRect(head.x * grid, head.y * grid, grid, grid);
        if (directions.length >= size) {
          ctx.fillStyle = 'lightgreen';
          ctx.fillRect(tail.x * grid, tail.y * grid, grid, grid);
          switch (directions.shift()) {
            case 'left':
              tail.x--;
              break;
            case 'up':
              tail.y--;
              break;
            case 'right':
              tail.x++;
              break;
            case 'down':
              tail.y++;
              break;
          }
        }
        // console.log(food, head);
        if (head.x == food.x && head.y == food.y) {
          food.x = Math.floor(Math.random() * grid);
          food.y = Math.floor(Math.random() * grid);
        }
      }
      document.addEventListener('keydown', main);
<!DOCTYPE html>
<html lang="pt-br">
  <head>
    <title>Jogo da cobrinha</title>
    <meta charset="utf-8" />
    <meta name="author" content="Tomás Ricardo" />
  </head>
  <body>
    <canvas id="canvas" width="400" height="400"></canvas>
  </body>
</html>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.