Creating a production-level Snake game within a single HTML document involves organizing the code efficiently using HTML, CSS, and JavaScript. Below is a complete implementation that includes a responsive game canvas, smooth animations, user input handling, collision detection, scoring, and game-over functionality.
You can copy the following code into a single .html file and open it in your browser to play the game.
Responsive Canvas: The canvas is set to 400x400 pixels, but you can adjust the canvasSize variable for different dimensions.
Game Loop: Utilizes setInterval to control the game loop's update and draw cycles based on the current speed.
Snake Movement: The snake moves based on arrow key inputs with direction changes properly handled to prevent reversing.
Apple Placement: Apples are randomly placed on the grid, ensuring they do not appear on the snake's body.
Collision Detection: The game detects collisions with the snake itself and ends the game accordingly.
Scoring System: Keeps track of the player's score, increases it when the snake eats an apple, and displays it on the screen.
Increasing Difficulty: The snake's speed increases every 5 points to increase the game's difficulty progressively.
Game Over Screen: A modal appears when the game ends, showing the final score and providing a restart button.
Styling: Basic but clean styling for the game canvas, score display, and game-over modal to enhance the user experience.
How to Play:
Use the Arrow Keys on your keyboard to control the direction of the snake.
Eat the red apples to grow the snake and increase your score.
Avoid colliding with the snake's own body; otherwise, the game will end.
Press the Restart button on the game-over screen to play again.
Customization:
Canvas Size: Change the canvasSize variable (both width and height) to make the game area larger or smaller.
Grid Size: Modify the grid variable to change the size of each cell in the grid.
Initial Speed: Adjust the speed variable to make the snake start faster or slower.
Styling: Enhance the CSS section to modify colors, fonts, or add additional effects.
Code Organization:
Immediately Invoked Function Expression (IIFE): Encapsulates the game logic to avoid global namespace pollution.
Event Listeners: Handles keyboard inputs and restart button actions efficiently.
Modular Functions: Separates concerns by dividing the code into functions like init, resetGame, gameLoop, update, draw, changeDirection, placeApple, and endGame.
This implementation provides a solid foundation for a Snake game and can be further enhanced with additional features such as high score tracking, different levels, or advanced graphics.