This project implements a classic Snake Game using JavaScript and the HTML5 Canvas API. Players control a snake that grows longer as it eats apples, avoiding collisions with the edges of the game area.
Author: Alistair Chambers
Date: 12/15/21
File: snake.js
The snake moves continuously, eating apples to grow longer. The player must guide the snake without hitting the edges of the canvas. The game includes a scoring system and supports pausing or restarting the gameplay.
- Smooth Gameplay: Continuous movement with a simple game loop.
- Apple Respawn: Apples appear at random locations, avoiding the snake’s body.
- Collision Handling: The snake wraps around the canvas edges.
- Score Tracking: Displays the player's score based on the snake's length.
- Pause/Restart: Players can pause the game or restart with a new snake.
- Arrow Keys: Move the snake.
- Shift Key: Pause/Unpause the game.
- Spacebar: Reset the game.
- Download the project files.
- Open the
index.html
file in a modern browser. - The game will start automatically. Use the controls to play.
Represents the snake, including its position, size, and movement logic.
-
Attributes:
x
,y
: Starting position.size
: Size of each segment.tail
: Array storing the snake's body segments.rotateX
,rotateY
: Direction of movement.
-
Methods:
move()
: Updates the snake's position based on its direction.
Handles the apple's random placement, ensuring it doesn't spawn on the snake's body.
- Attributes:
x
,y
: Position.size
: Size of the apple.color
: Appearance.
gameLoop()
: Starts the main game loop.update()
: Updates game elements like snake movement and collision detection.draw()
: Renders the game elements on the canvas.checkHitWall()
: Wraps the snake around the canvas edges.eatApple()
: Checks if the snake eats the apple and grows its tail.createRect(x, y, width, height, color)
: Draws rectangles for game elements.
keydown
: Handles player input for movement, pausing, and restarting.
- Game Over Mechanic: End the game when the snake collides with itself.
- Difficulty Levels: Increase speed as the score increases.
- Graphics Enhancements: Add textures or animations.
- High Scores: Track and display the top scores.
- Mobile Support: Add touch controls for mobile devices.
This project is open-source and can be used or modified under the terms of the MIT License.