Javascript Snake Game

Javascript Snake Game

Creating a JavaScript Snake Game involves using HTML for the structure, CSS for styling, and JavaScript for the game logic. Here’s a simple example of a Snake Game:

HTML (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>
    <div id="game-board"></div>
    <script src="script.js"></script>
</body>
</html>

CSS (style.css):

#game-board {
    display: grid;
    grid-template-columns: repeat(20, 20px);
    grid-template-rows: repeat(20, 20px);
}
.snake, .food {
    width: 20px;
    height: 20px;
}
.snake {
    background-color: green;
}
.food {
    background-color: red;
}

JavaScript (script.js):

document.addEventListener('DOMContentLoaded', () => {
    const board = document.getElementById('game-board');
    const gridSize = 20;
    let snake = [{ x: 10, y: 10 }];
    let food = getRandomPosition();

    function draw() {
        board.innerHTML = '';
        drawSnake();
        drawFood();
    }

    function drawSnake() {
        snake.forEach(segment => {
            const snakeElement = createGameElement('div', 'snake');
            snakeElement.style.gridRowStart = segment.y;
            snakeElement.style.gridColumnStart = segment.x;
            board.appendChild(snakeElement);
        });
    }

    function drawFood() {
        const foodElement = createGameElement('div', 'food');
        foodElement.style.gridRowStart = food.y;
        foodElement.style.gridColumnStart = food.x;
        board.appendChild(foodElement);
    }

    function createGameElement(tagName, className) {
        const element = document.createElement(tagName);
        element.className = className;
        return element;
    }

    function getRandomPosition() {
        return {
            x: Math.floor(Math.random() * gridSize) + 1,
            y: Math.floor(Math.random() * gridSize) + 1
        };
    }

    function move() {
        const head = { ...snake[0] };
        switch (direction) {
            case 'UP':
                head.y--;
                break;
            case 'DOWN':
                head.y++;
                break;
            case 'LEFT':
                head.x--;
                break;
            case 'RIGHT':
                head.x++;
                break;
        }

        if (head.x === food.x && head.y === food.y) {
            snake.push({});
            food = getRandomPosition();
        }

        snake.unshift(head);
        snake.pop();
    }

    function checkCollision() {
        const head = snake[0];
        return (
            head.x < 1 || head.x > gridSize ||
            head.y < 1 || head.y > gridSize ||
            snake.slice(1).some(segment => segment.x === head.x && segment.y === head.y)
        );
    }

    let direction = 'RIGHT';

    window.addEventListener('keydown', event => {
        switch (event.key) {
            case 'ArrowUp':
                direction = 'UP';
                break;
            case 'ArrowDown':
                direction = 'DOWN';
                break;
            case 'ArrowLeft':
                direction = 'LEFT';
                break;
            case 'ArrowRight':
                direction = 'RIGHT';
                break;
        }
    });

    function gameLoop() {
        move();
        if (checkCollision()) {
            alert('Game Over!');
            snake = [{ x: 10, y: 10 }];
            direction = 'RIGHT';
        }
        draw();
    }

    setInterval(gameLoop, 200);
});

This is a basic implementation, and you can enhance it further by adding features such as score tracking, increasing difficulty, or adding sound effects.

"appId" and "appKey" is required, otherwise comment won't work.
Get your APP-ID and APP-Key

Related Posts

Exploring The ForEach Loop In JavaScript

Exploring The ForEach Loop In JavaScript

Working with arrays is such an important part of writing JavaScript. We’re always looping through them to filter data, transform it, or process it in some way.

Read More
Testing and Debugging in React

Testing and Debugging in React

In the world of web development, testing and debugging are indispensable processes that ensure the reliability and quality of your applications.

Read More
React Styling: Inline, Classes, Modules, Frameworks, and CSS-in-JS

React Styling: Inline, Classes, Modules, Frameworks, and CSS-in-JS

In React, there are several options for styling your components and user interfaces. Here are three common approaches: inline styles, CSS classes, and CSS modules.

Read More
10 Handy React.js Code Snippets for Your Projects

10 Handy React.js Code Snippets for Your Projects

Here are 10 useful React.js code snippets that can come in handy for various scenarios. You can adapt and use these snippets in your React projects:

Read More
React Router Mastery: Dynamic SPAs Made Easy

React Router Mastery: Dynamic SPAs Made Easy

React Router is a library that provides routing capabilities to your React applications. It allows you to create single-page applications (SPAs) with multiple views or pages, each represented by its own component.

Read More
React Context API and Prop Drilling with Examples

React Context API and Prop Drilling with Examples

Context API In the modern web development, building dynamic and interactive user interfaces is a crucial aspect. A significant challenge that developers face is managing the state of an application efficiently and ensuring that this state is accessible across various components without resorting to complex and error-prone prop passing.

Read More