Whtmlets/js2020/Jakhangirov/index.html

Материал из Department of Theoretical and Applied Mechanics
Перейти к: навигация, поиск

Описание[править]

Генератор лабиринта на JavaScript

Исполнитель: Джахангиров Мансур

Группа 3630103/90001 Кафедра Теоретической механики

Визуализация[править]

Код программы[править]

Код программы на языке JavaScript:
  1 const canvas = document.getElementById("game");
  2 const ctx = canvas.getContext("2d");
  3 
  4 const ground = new Image();
  5 ground.src = "img/ground.png";
  6 
  7 const foodImg = new Image();
  8 foodImg.src = "img/food.png";
  9 
 10 let box = 32;
 11 
 12 let score = 0;
 13 
 14 let food = {
 15   x: Math.floor((Math.random() * 17 + 1)) * box,
 16   y: Math.floor((Math.random() * 15 + 3)) * box,
 17 };
 18 
 19 let snake = [];
 20 snake[0] = {
 21   x: 9 * box,
 22   y: 10 * box
 23 };
 24 
 25 document.addEventListener("keydown", direction);
 26 
 27 let dir;
 28 
 29 function direction(event) {
 30   if(event.keyCode == 37 && dir != "right")
 31     dir = "left";
 32   else if(event.keyCode == 38 && dir != "down")
 33     dir = "up";
 34   else if(event.keyCode == 39 && dir != "left")
 35     dir = "right";
 36   else if(event.keyCode == 40 && dir != "up")
 37     dir = "down";
 38 }
 39 
 40 function eatTail(head, arr) {
 41   for(let i = 0; i < arr.length; i++) {
 42     if(head.x == arr[i].x && head.y == arr[i].y)
 43       clearInterval(game);
 44   }
 45 }
 46 
 47 function drawGame() {
 48   ctx.drawImage(ground, 0, 0);
 49 
 50   ctx.drawImage(foodImg, food.x, food.y);
 51 
 52   for(let i = 0; i < snake.length; i++) {
 53     ctx.fillStyle = i == 0 ? "blue" : "orange";
 54     ctx.fillRect(snake[i].x, snake[i].y, box, box);
 55   }
 56 
 57   ctx.fillStyle = "black";
 58   ctx.font = "50px Times New Roman";
 59   ctx.fillText(score, box * 2.5, box * 1.7);
 60 
 61   let snakeX = snake[0].x;
 62   let snakeY = snake[0].y;
 63 
 64   if(snakeX == food.x && snakeY == food.y) {
 65     score++;
 66     food = {
 67       x: Math.floor((Math.random() * 17 + 1)) * box,
 68       y: Math.floor((Math.random() * 15 + 3)) * box,
 69     };
 70   } else {
 71     snake.pop();
 72   }
 73 
 74   if(snakeX < box || snakeX > box * 17
 75     || snakeY < 3 * box || snakeY > box * 17)
 76     clearInterval(game);
 77 
 78   if(dir == "left") snakeX -= box;
 79   if(dir == "right") snakeX += box;
 80   if(dir == "up") snakeY -= box;
 81   if(dir == "down") snakeY += box;
 82 
 83   let newHead = {
 84     x: snakeX,
 85     y: snakeY
 86   };
 87 
 88   eatTail(newHead, snake);
 89 
 90   snake.unshift(newHead);
 91 }
 92 
 93 let game = setInterval(drawGame, 100);
 94 
 95 
 96 
 97 
 98 
 99 
100 //