JSFiddle - React, Tailwind, and code Playground
by rga4
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Snake Game</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="300"></canvas>
<p>Score: <span id="score">0</span></p> <!-- Add this line -->
<script src="snake.js"></script>
</body>
</html>
JavaScript
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
let snake = [{x: 200, y: 150}, {x: 190, y: 150}, {x: 180, y: 150}];
let direction = 'right';
let food = {x: Math.floor(Math.random() * 39) * 10 + 5, y: Math.floor(Math.random() * 29) * 10 + 15};
let score = 0;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawSnake();
drawFood();
checkCollision();
updateScore();
requestAnimationFrame(draw);
}
function drawSnake() {
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = (i === 0) ? 'green' : 'white';
ctx.fillRect(snake[i].x, snake[i].y, 10, 10);
}
}
function drawFood() {
ctx.fillStyle = 'red';
ctx.fillRect(food.x, food.y, 10, 10);
}
function moveSnake() {
let head = {x: snake[0].x, y: snake[0].y};
switch (direction) {
case 'up':
head.y -= 10;
break;
case 'down':
head.y += 10;
break;
case 'left':
head.x -= 10;
break;
case 'right':
head.x += 10;
break;
}
snake.unshift(head);
if (snake[0].x !== food.x || snake[0].y !== food.y) {
snake.pop();
} else {
food = {x: Math.floor(Math.random() * 39) * 10 + 5, y: Math.floor(Math.random() * 29) * 10 + 15};
score++;
}
}
function updateScore() {
document.getElementById('score').innerText = `Score: ${score}`;
}
function checkCollision() {
for (let i = 1; i < snake.length; i++) {
if (snake[0].x === snake[i].x && snake[0].y === snake[i].y) {
gameOver();
}
}
if (snake[0].x < 0 || snake[0].x > 390 || snake[0].y < 0 || snake[0].y > 290) {
gameOver();
}
}
function gameOver() {
alert(`Game Over! Your score was ${score}.`);
resetGame();
}
function resetGame() {
snake = [{x: 200, y: 150}, {x: 190, y: 150}, {x: 180, y: 150}];
direction = 'right';
food = {x:...