Skip to content

Instantly share code, notes, and snippets.

@Karnak19
Created October 8, 2019 19:59
Show Gist options
  • Select an option

  • Save Karnak19/4f97dc36b9f0a0ca4e0b7615d55bfd1c to your computer and use it in GitHub Desktop.

Select an option

Save Karnak19/4f97dc36b9f0a0ca4e0b7615d55bfd1c to your computer and use it in GitHub Desktop.
JS Snake
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Snake</title>
</head>
<body>
<canvas id="game" width="400" height="400"></canvas>
<h1 id="score"></h1>
<script>
let titleScore = document.getElementById("score");
window.onload = () => {
canvas = document.getElementById("game");
context = canvas.getContext("2d");
document.addEventListener("keydown", keyPush);
setInterval(game, 1000 / 15);
};
let playerX = 10;
let playerY = 10;
let gridSize = 20;
let tailCount = 20;
let appleX = Math.floor(Math.random() * tailCount);
let appleY = Math.floor(Math.random() * tailCount);
let xVelocity = 0;
let yVelocity = 0;
let trail = [];
let tail = 5;
const game = () => {
playerX += xVelocity;
playerY += yVelocity;
if (playerX < 0) {
playerX = tailCount - 1;
}
if (playerX > tailCount - 1) {
playerX = 0;
}
if (playerY < 0) {
playerY = tailCount - 1;
}
if (playerY > tailCount - 1) {
playerY = 0;
}
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "lime";
for (let i = 0; i < trail.length; i++) {
context.fillRect(trail[i].x * gridSize, trail[i].y * gridSize, gridSize - 2, gridSize - 2);
if (trail[i].x == playerX && trail[i].y == playerY) {
tail = 5;
titleScore.innerHTML = `Score : ${tail - 5}`;
}
}
trail.push({ x: playerX, y: playerY });
while (trail.length > tail) {
trail.shift();
}
if (appleX == playerX && appleY == playerY) {
tail++;
titleScore.innerHTML = `Score : ${tail - 5}`;
appleX = Math.floor(Math.random() * tailCount);
appleY = Math.floor(Math.random() * tailCount);
}
context.fillStyle = "red";
context.fillRect(appleX * gridSize, appleY * gridSize, gridSize - 2, gridSize - 2);
};
const keyPush = e => {
switch (e.keyCode) {
case 37:
xVelocity = -1;
yVelocity = 0;
break;
case 38:
xVelocity = 0;
yVelocity = -1;
break;
case 39:
xVelocity = 1;
yVelocity = 0;
break;
case 40:
xVelocity = 0;
yVelocity = 1;
break;
default:
break;
}
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment