0

Пыталась на основе туториала создать игру змейку. И вроде бы весь код проверила, но не могу найти ошибку. На экране никакая игра не выдается, с чем это может быть связано?описание ошибки в консоли

1) указывает, что в файле snake ошибка в 48 строке. там собственно помещен for цикл и с ним все в порядке. 2) говорит, что не определен метод drawModule, хотя в файле snake он также прекрасно определен. при запуске кода на stackoverflow, говорит, что ошибка именно в 42ой строкекак хранятся файлы, в папке Js все три файла отдельно.

//файл snake.js
var drawModule = (function() {

  var bodySnake = function(x, y) {
    //the square
    ctx.fillStyle = 'green';
    ctx.fillRect(x * snakeSize, y * snakeSize, snakeSize, snakeSize);
    //The border of the square, draws rect with no fill
    ctx.strokeStyle = 'yellow'; //set & return the color
    ctx.strokeRect = (x * snakeSize, y * snakeSize, snakeSize, snakeSize);
  }

  var pizza = function(x, y) {
    ctx.fillStyle = 'yellow';
    ctx.fillRect(x * snakeSize, y * snakeSize, snakeSize, snakeSize);
    ctx.fillStyle = 'red';
    ctx.fillRect(x * snakeSize + 1, y * snakeSize + 1, snakeSize - 2, snakeSize - 2);
  }

  var scoreText = function() {
    //The amount of pizzas the snake eat
    var score_text = "Score: " + score;
    ctx.fillStyle = 'blue'; //fill the drawing
    ctx.fillText(score_text, 145, h - 5); //the col for txt
  }


  //The snake's structure made of array

  var drawSnake = function() {
    var length = 4; //the size of snake
    snake = [];

    for (var i = length - 1; i >= 0; i--) {
      snake.push({
        x: i,
        y: 0
      });
    }
  }

  //The food has random position and can not overlap the position of a snake
  var createFood = function() {
    food = {
      x: Math.floor((Math.random() * 30) + 1),
      y: Math.floor((Math.random() * 30) + 1)
    }

    for (var i = 0; i > snake.length, i++) {
      var snakeX = snake[i].x;
      var snakeY = snake[i].y;

      if (food.x === snakeX || food.y === snakeY || food.y === snakeY && food.x === snakeX) {
        food.x = Math.floor((Math.random() * 30) + 1);
        food.y = Math.floor((Math.random() * 30) + 1);
      }
    }
  }

  //To check whether snake crashes into itself
  var checkCollision = function(x, y, array) {
    for (var i = 0; i < array.length; i++) {
      if (array[i].x === x && array[i].y === y)
        return true;
    }
    return false;
  }

  //Main function

  var paint = function() {
    ctx.fillStyle = 'light grey';
    ctx.fillRect(0, 0, w, h);
    //the border
    ctx.strokeStyle = 'black';
    ctx.strokeRect = (0, 0, w, h);

    //Disable the start button when the snake runs

    btn.setAttribute('disabled', true);
    var snakeX = snake[0].x;
    var snakeY = snake[0].y;

    if (direction == 'right') {
      snakeX++;
    } else if (direction == 'left') {
      snakeX--;
    } else if (direction == 'up') {
      snakeY--;
    } else if (direction == 'down') {
      snakeY++;
    }

    if (snakeX == -1 || snakeX == w / snakeSize || snakeY == -1 || snakeY == h / snakeSize || checkCollision(snakeX, snakeY, snake)) {
      //stop the game. start button is enebled.
      btn.removeAttribute('disabled', true);

      ctx.clearRect(0, 0, w, h);
      gameloop = clearInterval(gameloop);
      return;
    }

    if (snakeX == food.x && snakeY == food.y) {
      //New square for snake
      var tail = {
        x: snakeX,
        y: snakeY
      };
      score++;

      //Create new food
      createFood();
    } else {
      //the last cell
      var tail = snake.pop();
      tail.x = snakeX;
      tail.y = snakeY;
    }

    //puts the tail as the first cell.
    snake.unshift(tail);

    //for each element of array create a square using the bodySnake func 
    for (var i = 0; i < snake.length; i++) {
      bodySnake(snake[i].x, snake[i].y);
    }

    // create food 
    pizza(food.x, food.y);
    scoreText();
  }



  var init = function() {
    direction = 'down';
    drawSnake();
    createFood();
    gameloop = setInterval(paint, 80);
  }
  return {
    init: init
  };

}());

//Другой файл settings.js
var mycanvas = document.getElementById('canvas');
var ctx = mycanvas.getContext('2d');

var snakeSize = 7;
var w = 350;
var h = 350;
var score = 0;
var snake;

var food;

//другой файл app.js 
(function(window, document, drawModule, undefined) {

  //Connect the button in the html with the _init_ function
  var btn = document.getElementById('btn');
  btn.addEventListener("click", function() {
    drawModule.init();
  });

  document.onkeydown = function(event) {
    keyCode = window.event.keyCode;
    keyCode = event.keyCode;

    switch (keyCode) {
      case 37:
        if (direction != 'right') {
          direction = 'left';
          console.log('left');
        }
        break;
      case 39:
        if (direction != 'left') {
          direction = 'right';
          console.log('right');
        }
        break;
      case 38:
        if (direction != 'down') {
          direction = 'up';
          console.log('up');
        }
        break;

      case 40:
        if (direction != 'up') {
          direction = 'down';
          console.log('down');
        }
        break;
    }
  }


})(window, document, drawModule);
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset='utf-8' />
  <title>Snake Game</title>
</head>

<body>
  <canvas id="canvas" width="350" height="350"></canvas>
  <p>Press START and eat the pizza!</p>
  <button id="btn">START</button>

  <script src="js/settings.js"></script>
  <script src="js/snake.js"></script>
  <script src="js/app.js"></script>

</body>

</html>

1
  • Также возник вопрос собственно по коду. Подскажите, пожалуйста, как работает метод checkCollision. У данной функции три параметра, третий параметр array. Как программа узнает, что мы кладем в этот параметр именно массив квадратов, из которых состоит змея? Кто и как передает туда значение? 10 сен 2018 в 20:57

1 ответ 1

7

Читайте первую ошибку. Там говорит, что у вас синтаксическая ошибка в строке 49.

А именно в:

for (var i = 0; i > snake.length, i++) {

Должна быть точка с запятой:

for (var i = 0; i > snake.length; i++) {

//файл snake.js
var drawModule = (function() {

  var bodySnake = function(x, y) {
    //the square
    ctx.fillStyle = 'green';
    ctx.fillRect(x * snakeSize, y * snakeSize, snakeSize, snakeSize);
    //The border of the square, draws rect with no fill
    ctx.strokeStyle = 'yellow'; //set & return the color
    ctx.strokeRect = (x * snakeSize, y * snakeSize, snakeSize, snakeSize);
  }

  var pizza = function(x, y) {
    ctx.fillStyle = 'yellow';
    ctx.fillRect(x * snakeSize, y * snakeSize, snakeSize, snakeSize);
    ctx.fillStyle = 'red';
    ctx.fillRect(x * snakeSize + 1, y * snakeSize + 1, snakeSize - 2, snakeSize - 2);
  }

  var scoreText = function() {
    //The amount of pizzas the snake eat
    var score_text = "Score: " + score;
    ctx.fillStyle = 'blue'; //fill the drawing
    ctx.fillText(score_text, 145, h - 5); //the col for txt
  }


  //The snake's structure made of array

  var drawSnake = function() {
    var length = 4; //the size of snake
    snake = [];

    for (var i = length - 1; i >= 0; i--) {
      snake.push({
        x: i,
        y: 0
      });
    }
  }

  //The food has random position and can not overlap the position of a snake
  var createFood = function() {
    food = {
      x: Math.floor((Math.random() * 30) + 1),
      y: Math.floor((Math.random() * 30) + 1)
    }

    for (var i = 0; i > snake.length; i++) {
      var snakeX = snake[i].x;
      var snakeY = snake[i].y;

      if (food.x === snakeX || food.y === snakeY || food.y === snakeY && food.x === snakeX) {
        food.x = Math.floor((Math.random() * 30) + 1);
        food.y = Math.floor((Math.random() * 30) + 1);
      }
    }
  }

  //To check whether snake crashes into itself
  var checkCollision = function(x, y, array) {
    for (var i = 0; i < array.length; i++) {
      if (array[i].x === x && array[i].y === y)
        return true;
    }
    return false;
  }

  //Main function

  var paint = function() {
    ctx.fillStyle = 'light grey';
    ctx.fillRect(0, 0, w, h);
    //the border
    ctx.strokeStyle = 'black';
    ctx.strokeRect = (0, 0, w, h);

    //Disable the start button when the snake runs

    btn.setAttribute('disabled', true);
    var snakeX = snake[0].x;
    var snakeY = snake[0].y;

    if (direction == 'right') {
      snakeX++;
    } else if (direction == 'left') {
      snakeX--;
    } else if (direction == 'up') {
      snakeY--;
    } else if (direction == 'down') {
      snakeY++;
    }

    if (snakeX == -1 || snakeX == w / snakeSize || snakeY == -1 || snakeY == h / snakeSize || checkCollision(snakeX, snakeY, snake)) {
      //stop the game. start button is enebled.
      btn.removeAttribute('disabled', true);

      ctx.clearRect(0, 0, w, h);
      gameloop = clearInterval(gameloop);
      return;
    }

    if (snakeX == food.x && snakeY == food.y) {
      //New square for snake
      var tail = {
        x: snakeX,
        y: snakeY
      };
      score++;

      //Create new food
      createFood();
    } else {
      //the last cell
      var tail = snake.pop();
      tail.x = snakeX;
      tail.y = snakeY;
    }

    //puts the tail as the first cell.
    snake.unshift(tail);

    //for each element of array create a square using the bodySnake func 
    for (var i = 0; i < snake.length; i++) {
      bodySnake(snake[i].x, snake[i].y);
    }

    // create food 
    pizza(food.x, food.y);
    scoreText();
  }



  var init = function() {
    direction = 'down';
    drawSnake();
    createFood();
    gameloop = setInterval(paint, 80);
  }
  return {
    init: init
  };

}());

//Другой файл settings.js
var mycanvas = document.getElementById('canvas');
var ctx = mycanvas.getContext('2d');

var snakeSize = 7;
var w = 350;
var h = 350;
var score = 0;
var snake;

var food;

//другой файл app.js 
(function(window, document, drawModule, undefined) {

  //Connect the button in the html with the _init_ function
  var btn = document.getElementById('btn');
  btn.addEventListener("click", function() {
    drawModule.init();
  });

  document.onkeydown = function(event) {
    keyCode = window.event.keyCode;
    keyCode = event.keyCode;

    switch (keyCode) {
      case 37:
        if (direction != 'right') {
          direction = 'left';
          console.log('left');
        }
        break;
      case 39:
        if (direction != 'left') {
          direction = 'right';
          console.log('right');
        }
        break;
      case 38:
        if (direction != 'down') {
          direction = 'up';
          console.log('up');
        }
        break;

      case 40:
        if (direction != 'up') {
          direction = 'down';
          console.log('down');
        }
        break;
    }
  }


})(window, document, drawModule);
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset='utf-8' />
  <title>Snake Game</title>
</head>

<body>
  <canvas id="canvas" width="350" height="350"></canvas>
  <p>Press START and eat the pizza!</p>
  <button id="btn">START</button>

  <script src="js/settings.js"></script>
  <script src="js/snake.js"></script>
  <script src="js/app.js"></script>

</body>

</html>

3
  • 1
    глаз - алмаз :)
    – user176262
    10 сен 2018 в 15:49
  • действительно, сколько на эту строку смотрела, понять не могла, в чем дело. у меня также возник вопрос: почему нельзя скрипт в один файл поместить, зачем делить на 3 части? для удобства? 10 сен 2018 в 17:29
  • @МайяБареева да, для удобства. Когда у вас будет много кода, очень удобно, когда они в разных файлах. 11 сен 2018 в 5:27

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.