Я допиливал вчерашнюю игру змейка. Но столкнулся проблемой. Когда змейка кушает яблоко не срабатывается функция.
Вот код:
var canvas = document.getElementById("game");
var ctx = canvas.getContext("2d");
var box = 10;
//Snake
var snake = [];
var px = canvas.width / 2;
var py = canvas.height / 2;
var dir = "right";
var maxCell = 10;
var can = canvas.getBoundingClientRect();
//Apple
var ax = Math.floor(Math.random() * ~~(canvas.width / box));
var ay = Math.floor(Math.random() * ~~(canvas.height / box));
document.addEventListener("keydown", function (e) {
if (e.keyCode === 37 && dir !== "right") {
dir = "left";
//console.log('left')
} else if (e.keyCode === 38 && dir !== "down") {
dir = "up";
//console.log('up')
} else if (e.keyCode === 39 && dir !== "left") {
dir = "right";
//console.log('right')
} else if (e.keyCode === 40 && dir !== "up") {
dir = "down";
//console.log('down')
}
});
function direction() {
if (dir == "right") {
px += box;
} else if (dir == "left") {
px -= box;
} else if (dir == "up") {
py -= box;
} else if (dir == "down") {
py += box;
}
}
//Closure )))
function Elems() {
//! Spawn apple
function Apple() {
ctx.fillStyle = "green";
ctx.fillRect(ax, ay, box, box);
}
//! Spawn snake
function Snake() {
direction();
var head = {
x: px,
y: py,
};
snake.unshift(head);
if (snake.length < maxCell) {
snake.push({ x: px, y: py });
}
if (px >= canvas.width) {
px = 0;
} else if (px < 0) {
px = canvas.width;
}
if (py >= canvas.height) {
py = 0;
} else if (py < 0) {
py = canvas.height;
}
snake.forEach(function (elem, index) {
ctx.fillStyle = `red`;
ctx.fillRect(elem.x, elem.y, box, box);
});
//--------------------НЕРАБОЧИЙ КОД ------------------------------
if (head.x == ax && head.y == ay) {
alert("HI");
}
//-------------------------------------------------------------------------
snake.pop();
}
Snake();
Apple();
}
function loop() {
setInterval(() => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
Elems();
}, 2000 / 30);
}
loop();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
canvas {
border: 1px solid #000;
background-color: #000;
}
</style>
</head>
<body>
<canvas id="game" width="450" height="450"> </canvas>
<script src="./snake.js"></script>
</body>
</html>