Skip to content

Instantly share code, notes, and snippets.

@jessenich
Created June 21, 2024 19:04
Show Gist options
  • Save jessenich/d8ccdb302de092ad368595e9a4e30b20 to your computer and use it in GitHub Desktop.
Save jessenich/d8ccdb302de092ad368595e9a4e30b20 to your computer and use it in GitHub Desktop.
JS Snake Game
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snake Game</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #000;
}
canvas {
border: 1px solid #fff;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script src="snake.js"></script>
</body>
</html>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const gridSize = 20;
const tileCount = canvas.width / gridSize;
let snake = [{ x: 10, y: 10 }];
let velocity = { x: 0, y: 0 };
let food = { x: 15, y: 15 };
let gameOver = false;
function drawGame() {
if (gameOver) {
ctx.fillStyle = 'red';
ctx.font = '50px Arial';
ctx.fillText('Game Over', canvas.width / 4, canvas.height / 2);
return;
}
setTimeout(drawGame, 10);
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, canvas.width, canvas.height);
moveSnake();
checkCollision();
drawSnake();
drawFood();
}
function moveSnake() {
const head = { x: snake[0].x + velocity.x, y: snake[0].y + velocity.y };
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
food = {
x: Math.floor(Math.random() * tileCount),
y: Math.floor(Math.random() * tileCount)
};
} else {
snake.pop();
}
}
function checkCollision() {
const head = snake[0];
if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) {
gameOver = true;
}
for (let i = 1; i < snake.length; i++) {
if (snake[i].x === head.x && snake[i].y === head.y) {
gameOver = true;
}
}
}
function drawSnake() {
ctx.fillStyle = 'lime';
for (let part of snake) {
ctx.fillRect(part.x * gridSize, part.y * gridSize, gridSize, gridSize);
}
}
function drawFood() {
ctx.fillStyle = 'red';
ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize);
}
document.addEventListener('keydown', event => {
switch (event.key) {
case 'ArrowUp':
if (velocity.y === 0) {
velocity = { x: 0, y: -1 };
}
break;
case 'ArrowDown':
if (velocity.y === 0) {
velocity = { x: 0, y: 1 };
}
break;
case 'ArrowLeft':
if (velocity.x === 0) {
velocity = { x: -1, y: 0 };
}
break;
case 'ArrowRight':
if (velocity.x === 0) {
velocity = { x: 1, y: 0 };
}
break;
}
});
drawGame();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment