Introduction

In this article, I’ll show you how to create a classic Snake game using HTML, CSS, and JavaScript. We’ll use HTML and CSS for the layout and style, and JavaScript to bring the game to life by controlling the snake's movement, detecting collisions, and updating the score.

Snake Game Setup

  1. HTML: Set up the basic structure with a <canvas> for the game area and a score display.
  2. CSS: Add minimal styling to center the game and make it visually appealing.
  3. JavaScript: Define the game logic, including the snake's movement, food generation, collision detection, and score updates.

HTML Code

<!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>
</head>
<body>
    <h1>Snake Game</h1>
    <canvas id="gameCanvas"></canvas>
    <button class="retry" onclick="restartGame()">Try Again</button>
    <p>Score: <span id="score">0</span></p>
    <script src="script.js"></script>
</body>

CSS Code

The CSS centers the game elements on the page and adds some styling to canvas and the "Try Again" button, which appears when the game ends.

body {
            display: flex;
            flex-direction: column;
            align-items: center;
            font-family: Arial, sans-serif;
            background-color: #333;
            color: #fff;
        }

        h1 {
            margin-top: 20px;
        }

        canvas {
            border: 2px solid #3725db;
            background-color: #000;
        }

        p {
            font-size: 1.5em;
            margin-top: 10px;
        }

        /* Style the Try Again button */
        .retry {
            display: none;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            padding: 15px 30px;
            font-size: 1.5em;
            color: #fff;
            background-color: #ff6347;
            border: none;
            border-radius: 10px;
            cursor: pointer;
        }

        .retry:hover {
            background-color: #ff4500;
        }

JavaScript Game Logic

The game logic is handled in the script.js file.

Initialize and Setup the Game Canvas and Variables

Define Game Logic and Drawing

Game Control Functions

Output

Snake Game

Enhancements

You might include more features.