Untitled
Anonymous
plain_text
02/24/2026 5:07 PM
4.5 KB
13
Indexable
<!DOCTYPE html>
<html>
<head>
<title>Minimalist Snake</title>
<style>
body { display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #1a1a1a; color: white; font-family: sans-serif; }
canvas { border: 5px solid #333; box-shadow: 0 0 20px rgba(0,0,0,0.5); background: #000; }
.info { position: absolute; top: 20px; text-align: center; }
</style>
</head>
<body>
<div class="info">
<h1>SNAKE</h1>
<p>Score: <span id="score">0</span></p>
</div>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
const scoreElement = document.getElementById("score");
const gridSize = 20;
const tileCount = canvas.width / gridSize;
let score = 0;
let dx = 0;
let dy = 0;
let snake = [{x: 10, y: 10}];
let food = {x: 5, y: 5};
// Main Game Loop
function main() {
if (hasGameEnded()) return alert(`Game Over! Score: ${score}`);
setTimeout(function onTick() {
clearCanvas();
drawFood();
advanceSnake();
drawSnake();
main();
}, 100);
}
function clearCanvas() {
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function drawSnake() {
ctx.fillStyle = "#4CAF50";
snake.forEach(part => ctx.fillRect(part.x * gridSize, part.y * gridSize, gridSize - 2, gridSize - 2));
}
function advanceSnake() {
const head = {x: snake[0].x + dx, y: snake[0].y + dy};
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
score += 10;
scoreElement.innerHTML = score;
createFood();
} else {
snake.pop();
}
}
function hasGameEnded() {
if (dx === 0 && dy === 0) return false; // Don't lose before starting
const hitLeftWall = snake[0].x < 0;
const hitRightWall = snake[0].x > tileCount - 1;
const hitTopWall = snake[0].y < 0;
const hitBottomWall = snake[0].y > tileCount - 1;
let selfBite = false;
for (let i = 4; i < snake.length; i++) {
if (snake[i].x === snake[0].x && snake[i].y === snake[0].y) selfBite = true;
}
return hitLeftWall || hitRightWall || hitTopWall || hitBottomWall || selfBite;
}
function createFood() {
food.x = Math.floor(Math.random() * tileCount);
food.y = Math.floor(Math.random() * tileCount);
}
function drawFood() {
ctx.fillStyle = "#FF5252";
ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize - 2, gridSize - 2);
}
document.addEventListener("keydown", (e) => {
if (e.key === "ArrowUp" && dy !== 1) { dx = 0; dy = -1; }
if (e.key === "ArrowDown" && dy !== -1) { dx = 0; dy = 1; }
if (e.key === "ArrowLeft" && dx !== 1) { dx = -1; dy = 0; }
if (e.key === "ArrowRight" && dx !== -1) { dx = 1; dy = 0; }
});
main();
</script>
</body>
</html>Editor is loading...
Leave a Comment