This project is a classic Snake Game built using HTML Canvas, CSS, and JavaScript. The game renders a moving snake inside a grid-based canvas where the player controls direction using keyboard arrow keys. Food appears randomly, and the snake grows longer when it eats. The game ends when the snake hits the wall or collides with itself. Overall, the project demonstrates real-time animation, game logic, and user interaction using core web technologies.
HTML
<canvas id="gameCanvas" width="400" height="400"></canvas>The HTML file defines the structure of the Snake game interface. A main container holds the game title, canvas, score display, and control buttons. The <canvas> element is the most important part, as it serves as the drawing surface for the snake and food. The score section updates dynamically as the player eats food. Restart and Play Again buttons allow the user to reset the game without refreshing the page. A hidden Game Over section appears only when the player loses. The layout is kept simple so the focus stays on gameplay. The script file is loaded at the bottom to ensure the DOM is ready before JavaScript executes. Overall, the HTML provides a clean and functional skeleton for the game.
CSS
.hidden {
display: none;
}The CSS controls the visual appearance of the Snake game. A dark background theme is used to give the game a modern arcade-style look. The canvas is styled with a border and contrasting background color so the snake and food stand out clearly. Text is centered for better readability and alignment. Buttons are styled with rounded corners, colors, and hover effects to improve user interaction. The .hidden class is used to toggle visibility of the Game Over screen dynamically. Margins and spacing ensure the UI elements don’t overlap the canvas. The styling remains lightweight to avoid affecting performance. Overall, the CSS enhances clarity and usability without distracting from gameplay.
JavaScript
game = setInterval(draw, 100);The JavaScript file contains the complete game logic and animation control. It initializes the snake’s position, direction, score, and randomly placed food. The draw() function clears the canvas and redraws the snake and food on every frame. Movement is controlled by keyboard events, updating the snake’s direction while preventing reverse motion. Each time the snake eats food, its length increases and the score updates. Collision detection checks for wall hits and self-intersection to trigger game over. The game loop runs using setInterval, creating continuous movement. Restart functions reset all variables and reinitialize the game state. JavaScript acts as the engine that connects user input, rendering, and game rules together.