Calculator Tools Calculator Tools
Create

Snake Game

Sep 23, 2023

About this app

Play the classic snake game

Snake Game

Related apps

Put this on your site

Source

                    <html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1">

<title>Snake Game</title>
<meta name="description" content="Play the classic snake game">
<meta name="keywords" content="snake game, classic game, arcade game">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

<script type="text/javascript">
try {
// App Javascript Goes Here. Place your entire script content inside the try block for error handling.
document.addEventListener("DOMContentLoaded", function() {
// Constants
const boardSize = 20; // Size of the game board
const squareSize = 25; // Size of each square in pixels
const speed = 150; // Speed of the snake in milliseconds

// Variables
let snake = [{ x: 10, y: 10 }]; // Initial position of the snake
let direction = "right"; // Initial direction of the snake
let food = { x: 15, y: 10 }; // Initial position of the food
let score = 0; // Initial score

// Generate the game board
function generateBoard() {
const board = document.getElementById("board");
board.style.width = `${boardSize * squareSize}px`;
board.style.height = `${boardSize * squareSize}px`;

for (let i = 0; i < boardSize; i++) {
for (let j = 0; j < boardSize; j++) {
const square = document.createElement("div");
square.className = "square";
square.style.width = `${squareSize}px`;
square.style.height = `${squareSize}px`;
square.style.left = `${j * squareSize}px`;
square.style.top = `${i * squareSize}px`;
board.appendChild(square);
}
}
}

// Draw the snake on the game board
function drawSnake() {
const squares = document.getElementsByClassName("square");

// Remove the previous snake from the board
for (let i = 0; i < squares.length; i++) {
squares[i].classList.remove("snake");
}

// Draw the snake on the board
for (let i = 0; i < snake.length; i++) {
const { x, y } = snake[i];
const index = y * boardSize + x;
squares[index].classList.add("snake");
}
}

// Move the snake
function moveSnake() {
const head = { ...snake[0] };

// Update the position of the head based on the direction
switch (direction) {
case "up":
head.y--;
break;
case "down":
head.y++;
break;
case "left":
head.x--;
break;
case "right":
head.x++;
break;
}

// Check if the snake has collided with the wall
if (head.x < 0 || head.x >= boardSize || head.y < 0 || head.y >= boardSize) {
gameOver();
return;
}

// Check if the snake has collided with itself
for (let i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
gameOver();
return;
}
}

// Check if the snake has eaten the food
if (head.x === food.x && head.y === food.y) {
score++;
generateFood();
} else {
// Remove the last segment of the snake
snake.pop();
}

// Add the new head to the snake
snake.unshift(head);

// Draw the snake on the board
drawSnake();
}

// Generate a random position for the food
function generateFood() {
const squares = document.getElementsByClassName("square");

// Remove the previous food from the board
for (let i = 0; i < squares.length; i++) {
squares[i].classList.remove("food");
}

// Generate a random position for the food
food.x = Math.floor(Math.random() * boardSize);
food.y = Math.floor(Math.random() * boardSize);

// Draw the food on the board
const index = food.y * boardSize + food.x;
squares[index].classList.add("food");
}

// Change the direction of the snake based on the key pressed
function changeDirection(event) {
switch (event.key) {
case "ArrowUp":
if (direction !== "down") {
direction = "up";
}
break;
case "ArrowDown":
if (direction !== "up") {
direction = "down";
}
break;
case "ArrowLeft":
if (direction !== "right") {
direction = "left";
}
break;
case "ArrowRight":
if (direction !== "left") {
direction = "right";
}
break;
}
}

// Game over
function gameOver() {
clearInterval(gameInterval);
alert("Game Over! Your score: " + score);
resetGame();
}

// Reset the game
function resetGame() {
snake = [{ x: 10, y: 10 }];
direction = "right";
score = 0;
generateFood();
drawSnake();
gameInterval = setInterval(moveSnake, speed);
}

// Initialize the game
function initializeGame() {
generateBoard();
generateFood();
drawSnake();
gameInterval = setInterval(moveSnake, speed);

// Add event listener for keydown event
document.addEventListener("keydown", changeDirection);
}

// Call the initializeGame function to start the game
initializeGame();
});

} catch (error) {
// This will throw the error to the parent window.
throw error;
}
</script>

<style>
/* App CSS Goes Here */
body {
background-color: #f7f7f7;
font-family: 'Roboto', sans-serif;
}

#main-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}

#board {
position: relative;
border: 2px solid #333;
}

.square {
position: absolute;
background-color: #fff;
border: 1px solid #ccc;
transition: background-color 0.2s;
}

.snake {
background-color: #333;
}

.food {
background-color: #ff6347;
}
</style>
</head>
<body>
<div id="main-container" class="container">
<div id="board"></div>
</div>
</body>
</html>