Meta Description" name="description" />
<!DOCTYPE html>
<html>
<head>
<title>Krishna Snake Game</title>
<style>
canvas {
background: black;
display: block;
margin: auto;
}
</style>
</head>
<body>
<h2 style="text-align:center;">π Krishna Snake Game</h2>
<canvas id="game" width="400" height="400"></canvas>
<script>
let canvas = document.getElementById("game");
let ctx = canvas.getContext("2d");
let box = 20;
let snake = [{x: 200, y: 200}];
let food = {
x: Math.floor(Math.random()*20)*box,
y: Math.floor(Math.random()*20)*box
};
let direction = "";
document.addEventListener("keydown", changeDirection);
function changeDirection(event){
if(event.key === "ArrowUp" && direction !== "DOWN") direction = "UP";
if(event.key === "ArrowDown" && direction !== "UP") direction = "DOWN";
if(event.key === "ArrowLeft" && direction !== "RIGHT") direction = "LEFT";
if(event.key === "ArrowRight" && direction !== "LEFT") direction = "RIGHT";
}
function draw(){
ctx.fillStyle = "black";
ctx.fillRect(0,0,400,400);
for(let i=0; i<snake.length; i++){
ctx.fillStyle = i==0 ? "lime" : "green";
ctx.fillRect(snake[i].x, snake[i].y, box, box);
}
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;
if(headX == food.x && headY == food.y){
food = {
x: Math.floor(Math.random()*20)*box,
y: Math.floor(Math.random()*20)*box
};
} else {
snake.pop();
}
let newHead = {x: headX, y: headY};
if(headX < 0 || headY < 0 || headX >= 400 || headY >= 400){
clearInterval(game);
alert("Game Over Krishna π’");
}
snake.unshift(newHead);
}
let game = setInterval(draw, 150);
</script>
</body>
</html>1
1
2KB
2KB
291.0ms
304.0ms
291.0ms