Here is an example of a basic snake game using JavaScript:
// canvas setup
var canvas = document.getElementById("snake-game");
var ctx = canvas.getContext("2d");
// game variables
var snake = [{x: 150, y: 150}];
var direction = "right";
var foodX = Math.floor(Math.random() * canvas.width);
var foodY = Math.floor(Math.random() * canvas.height);
var score = 0;
// game loop
setInterval(function() {
// clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw food
ctx.fillStyle = "red";
ctx.fillRect(foodX, foodY, 10, 10);
// move snake
var head = {x: snake[0].x, y: snake[0].y};
if (direction === "right") {
head.x += 10;
} else if (direction === "left") {
head.x -= 10;
} else if (direction === "up") {
head.y -= 10;
} else if (direction === "down") {
head.y += 10;
}
snake.unshift(head);
// check for collision with food
if (head.x === foodX && head.y === foodY) {
foodX = Math.floor(Math.random() * canvas.width);
foodY = Math.floor(Math.random() * canvas.height);
score++;
} else {
snake.pop();
}
// check for collision with walls
if (head.x >= canvas.width || head.x < 0 || head.y >= canvas.height || head.y < 0) {
alert("Game Over! Score: " + score);
location.reload();
}
// check for collision with self
for (var i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
alert("Game Over! Score: " + score);
location.reload();
}
}
// draw snake
ctx.fillStyle = "green";
for (var i = 0; i < snake.length; i++) {
ctx.fillRect(snake[i].x, snake[i].y, 10, 10);
}
}, 100);
// handle arrow key presses
document.onkeydown = function(event) {
if (event.keyCode === 37 && direction !== "right") {
direction = "left";
} else if (event.keyCode === 38 && direction !== "down") {
direction = "up";
} else if (event.keyCode === 39 && direction !== "left") {
direction = "right";
} else if (event.keyCode === 40 && direction !== "up") {
direction = "down";
}
};
This is a very basic example and you can add more features like:
changing the speed of the snake as the score increases
adding a pause and resume button
Comments
Post a Comment