Snake Game using HTML, CSS and JavaScript
![Snake Game using HTML, CSS and JavaScript](https://www.kingofjavascript.com/uploads/posts/thumbnails/snake_game_html_css_javascript_1280x720.jpg)
February 07, 2023
Learn How to Create Snake Game using HTML, CSS and JavaScript
today I'm going to teach you how to build Snake Game with JavaScript.
Follow the Steps:
Step 1) Add HTML:
Example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My Snake Game</title> </head> <body> <div class="container"> <h2 class="score"> Score : <span id="score">0</span></h2> <div class="game-board"></div> </div> </body> </html>
Step 2) Add CSS:
Example
*{ box-sizing: border-box; } body{ margin: 0; padding: 0; } .container{ height: 100vh; width: 100%; background: #000; display: flex; justify-content: center; align-items: center; flex-direction: column; } .game-board{ height: 90vmin; width: 90vmin; background: linear-gradient(orange, yellow); display: grid; grid-template-columns: repeat(16, 1fr); grid-template-rows: repeat(16, 1fr); } .score{ background: yellow; padding: 10px 20px; border-radius: 20px; } .snake{ background: #219d00; border: 2px solid #000; display: flex; align-items: center; justify-content: center; color: #fff; } .head{ background: url(snake.png); background-size: 100% 100%; display: flex; align-items: center; justify-content: center; color: #fff; z-index: 22; } .food{ background: url(apple.png); background-size: 100% 100%; z-index: 55; }
Step 3) Add Javascript:
example
var lastPaintTime = 0; let SNAKE_SPEED = 2; let inputDirection = { x: 0, y: 0 } let lastInputDirection = inputDirection; let gameOver = false; const EXPENTION_AMOUNT = 1; var score = 0; const snakeBody = [{ x: 8, y: 8 }, ]; let food = getFoodrandomPosition(); const gameBoard = document.querySelector(".game-board"); const scoreBox = document.getElementById("score"); function paint(currentTime) { var TimeSeconds = (currentTime - lastPaintTime) / 1000; requestAnimationFrame(paint); if (TimeSeconds < 1 / SNAKE_SPEED) return; lastPaintTime = currentTime; if (gameOver != true) { update(); draw(); } } window.requestAnimationFrame(paint); function draw() { drawSnake(); drawFood(); } function update() { gameBoard.innerHTML = ""; snakeMove(); snakeEatFood(); } function drawSnake() { snakeBody.forEach((segment, index) => { var snakeElement = document.createElement("div"); snakeElement.style.gridColumnStart = segment.x; snakeElement.style.gridRowStart = segment.y; // snakeElement.innerHTML = index; snakeElement.style.transform = "rotate(0deg)"; if (index == 0) { snakeElement.classList.add("head"); if (inputDirection.x == 1) { snakeElement.style.transform = "rotate(-90deg)"; } else if (inputDirection.x == -1) { snakeElement.style.transform = "rotate(90deg)"; } else if (inputDirection.y == -1) { snakeElement.style.transform = "rotate(180deg)"; } else if (inputDirection.y == 1) { snakeElement.style.transform = "rotate(0deg)"; } } else { snakeElement.classList.add("snake"); } gameBoard.appendChild(snakeElement); }); } function drawFood() { var foodElement = document.createElement("div"); foodElement.style.gridColumnStart = food.x; foodElement.style.gridRowStart = food.y; foodElement.classList.add("food"); gameBoard.appendChild(foodElement); } function snakeMove() { inputDirection = getInputDirection(); for (i = snakeBody.length - 2; i >= 0; i--) { snakeBody[i + 1] = { ...snakeBody[i] } } snakeBody[0].x += inputDirection.x; snakeBody[0].y += inputDirection.y; checkGameOver(); } function getInputDirection() { window.addEventListener("keydown", e => { switch (e.key) { case 'ArrowUp': if (lastInputDirection.y == 1) break; inputDirection = { x: 0, y: -1 } break; case 'ArrowDown': if (lastInputDirection.y == -1) break; inputDirection = { x: 0, y: 1 } break; case 'ArrowLeft': if (lastInputDirection.x == 1) break; inputDirection = { x: -1, y: 0 } break; case 'ArrowRight': if (lastInputDirection.x == -1) break; inputDirection = { x: 1, y: 0 } break; default: inputDirection = { x: 0, y: 0 } } }) lastInputDirection = inputDirection; return inputDirection; } function snakeEatFood() { if (isEat()) { score += 10; scoreBox.innerHTML = score; console.log("eated") food = getFoodrandomPosition(); SNAKE_SPEED++; expendSnake(); } } function isEat() { return snakeBody[0].x === food.x && snakeBody[0].y === food.y; } function getFoodrandomPosition() { let a, b, myCondition = true; while (myCondition) { a = Math.ceil(Math.random() * 16); b = Math.ceil(Math.random() * 16); myCondition = snakeBody.some(segment => { return segment.x === a && segment.y === b; }) } return { x: a, y: b }; } function expendSnake() { for (i = 0; i < EXPENTION_AMOUNT; i++) { snakeBody.push(snakeBody[snakeBody.length - 1]); } } function checkGameOver() { if (snakeOutOfGrid() || snakeIntersection()) { alert("Game Over : You Loose"); gameOver = true; location.reload(); } } function snakeOutOfGrid() { return snakeBody[0].x < 0 || snakeBody[0].x > 16 || snakeBody[0].y < 0 || snakeBody[0].y > 16; } function snakeIntersection() { for (i = 1; i < snakeBody.length; i++) { if (snakeBody[0].x === snakeBody[i].x && snakeBody[0].y === snakeBody[i].y) { return true; } } }