Snake Game
by SonicBear35120 lines2.4 KB
<!DOCTYPE html>
<html>
<head>
<title>Snake Game</title>
<style>
body {
margin: 0;
background: black;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
canvas {
background: #111;
border: 2px solid #0f0;
}
#score {
position: absolute;
top: 10px;
color: lime;
font-family: Arial;
font-size: 20px;
}
</style>
</head>
<body>
<div id="score">Score: 0</div>
<canvas id="game" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");
const box = 20;
let snake = [{x: 9 * box, y: 10 * box}];
let food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
};
let direction = "RIGHT";
let score = 0;
document.addEventListener("keydown", changeDirection);
function changeDirection(e) {
if (e.key === "ArrowUp" && direction !== "DOWN") direction = "UP";
else if (e.key === "ArrowDown" && direction !== "UP") direction = "DOWN";
else if (e.key === "ArrowLeft" && direction !== "RIGHT") direction = "LEFT";
else if (e.key === "ArrowRight" && direction !== "LEFT") direction = "RIGHT";
}
function drawGame() {
ctx.fillStyle = "#111";
ctx.fillRect(0, 0, 400, 400);
// snake
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = "lime";
ctx.fillRect(snake[i].x, snake[i].y, box, box);
}
// food
ctx.fillStyle = "red";
ctx.fillRect(food.x, food.y, box, box);
let headX = snake[0].x;
let headY = snake[0].y;
if (direction === "UP") headY -= box;
if (direction === "DOWN") headY += box;
if (direction === "LEFT") headX -= box;
if (direction === "RIGHT") headX += box;
// eat food
if (headX === food.x && headY === food.y) {
score++;
document.getElementById("score").innerText = "Score: " + score;
food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
};
} else {
snake.pop();
}
let newHead = {x: headX, y: headY};
// game over
if (
headX < 0 || headY < 0 ||
headX >= 400 || headY >= 400 ||
collision(newHead, snake)
) {
clearInterval(game);
alert("Game Over! Score: " + score);
}
snake.unshift(newHead);
}
function collision(head, array) {
for (let i = 0; i < array.length; i++) {
if (head.x === array[i].x && head.y === array[i].y) {
return true;
}
}
return false;
}
let game = setInterval(drawGame, 120);
</script>
</body>
</html>Game Source: Snake Game
Creator: SonicBear35
Libraries: none
Complexity: moderate (120 lines, 2.4 KB)
The full source code is displayed above on this page.
Remix Instructions
To remix this game, copy the source code above and modify it. Add a ARCADELAB header at the top with "remix_of: snake-game-sonicbear35" to link back to the original. Then publish at arcadelab.ai/publish.