so i made a snake game using ai with html and css and js i didn’t know how to i have only did it with python
styles.css
body {
background: #111;
color: white;
text-align: center;
font-family: Arial, sans-serif;
}
#gameCanvas {
background: #222;
border: 3px solid #0f0;
margin-top: 20px;
}
#gameCanvas {
border: 4px solid #0f0;
background: #111;
}
script.js
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
const box = 20;
const gridSize = 1000;
let snake = [{ x: 25 * box, y: 25 * box }];
let direction = "RIGHT";
function randomFood() {
return {
x: Math.floor(Math.random() * (gridSize / box)) * box,
y: Math.floor(Math.random() * (gridSize / box)) * box
};
}
let food = randomFood();
document.addEventListener("keydown", changeDirection);
function changeDirection(e) {
const key = e.key.toLowerCase();
if ((key === "arrowup" || key === "w") && direction !== "DOWN") direction = "UP";
else if ((key === "arrowdown" || key === "s") && direction !== "UP") direction = "DOWN";
else if ((key === "arrowleft" || key === "a") && direction !== "RIGHT") direction = "LEFT";
else if ((key === "arrowright" || key === "d") && direction !== "LEFT") direction = "RIGHT";
}
function drawGame() {
ctx.clearRect(0, 0, gridSize, gridSize);
ctx.fillStyle = "red";
ctx.fillRect(food.x, food.y, box, box);
let head = { ...snake[0] };
if (direction === "UP") head.y -= box;
if (direction === "DOWN") head.y += box;
if (direction === "LEFT") head.x -= box;
if (direction === "RIGHT") head.x += box;
if (
head.x < 0 || head.x >= gridSize ||
head.y < 0 || head.y >= gridSize ||
snake.some(segment => segment.x === head.x && segment.y === head.y)
) {
alert("Game Over!");
document.location.reload();
return;
}
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
food = randomFood();
} else {
snake.pop();
}
ctx.fillStyle = "#0f0";
snake.forEach(segment => {
ctx.fillRect(segment.x, segment.y, box, box);
});
}
ctx.strokeStyle = "#0f0";
ctx.lineWidth = 4;
ctx.strokeRect(0, 0, gridSize, gridSize);
setInterval(drawGame, 100);
index.html
<!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>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Snake Game</h1>
<canvas id="gameCanvas" width="1000" height="1000"></canvas>
<script src="script.js"></script>
</body>
</html>