Snake
Difficulty: Hard
In this challenge, you'll build a simplified version of the classic Snake game. The user controls a snake on a 7x7 grid, pressing buttons to move the snake, eat food, and grow. The game ends when the snake hits the wall or itself.
Overview
This is a single-screen game with the following components:
1️⃣ Game Grid – A 7x7 grid representing the playing field.
2️⃣ Snake Movement – The user presses buttons to move the snake in one of four directions.
3️⃣ Food (Apple) – Appears randomly on the grid; when eaten, the snake grows.
4️⃣ Collision Detection – Ends the game when the snake hits a wall or itself.
Requirements
Setup
- The snake always starts at the vertical center, on the very left of the grid at position
(row: 3, column: 0). - The snake's initial length is 3 segments, positioned horizontally.
Snake Movement
- Movement is controlled by four directional buttons.
- The snake moves one step at a time when a button is pressed. The snake does not move automatically—it only moves when the user presses a direction.
- The snake cannot reverse direction instantly (e.g., if moving right, pressing left should do nothing).
Food Mechanics
- A food item (🍎 apple) spawns randomly on the grid.
- When the snake eats the apple, it grows by one segment.
- A new apple is placed in a different random location after consumption. Apples cannot appear inside the snake's body.
Hint - How to grow the snake?
We can place the new segment where the apple was while keeping the tail stationary.
Game Over Conditions
- Moves outside the grid (hits a wall).
- Runs into itself (head collides with its own body).
- When the game ends, display a game over message and allow the user to restart.
Other Requirements
- The snake head should be visually distinct from its body.
- The apple should be easily recognizable and visually distinct from the snake.
Above & Beyond
Once the core functionality is complete, consider adding:
- The snake moves automatically instead of requiring button presses.
- Display the player’s current score based on apples eaten.
- Allow users to select different grid sizes.