0% found this document useful (0 votes)
5 views18 pages

Document

This document details a console-based implementation of the classic Snake game in C++, designed for Windows. It outlines the game's objectives, structure, and key programming concepts such as arrays, collision detection, and user input handling. The document also discusses potential enhancements and provides instructions for running the game.

Uploaded by

multiplecrown3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views18 pages

Document

This document details a console-based implementation of the classic Snake game in C++, designed for Windows. It outlines the game's objectives, structure, and key programming concepts such as arrays, collision detection, and user input handling. The document also discusses potential enhancements and provides instructions for running the game.

Uploaded by

multiplecrown3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

1. Introduction .............................................................................................................

2
2. Objectives................................................................................................................ 2
3. Program Overview..................................................................................................... 2
3.1 Game Area Setup................................................................................................. 2
3.2 Snake Representation .......................................................................................... 3
3.3 Food Representation............................................................................................ 3
3.4 Movement and Controls ....................................................................................... 3
3.5 Collision Detection .............................................................................................. 3
3.6 Growth and Scoring ............................................................................................. 3
3.7 Console Manipulation .......................................................................................... 4
4. Code Structure and Components .............................................................................. 4
5. Implementation Details............................................................................................. 4
6. Data Structures Used ................................................................................................ 5
7. Possible Enhancements ............................................................................................ 5
8. How to Use and Run.................................................................................................. 6
9. Data Structures and Algorithms (DSA) Concepts Used ................................................ 6
9.1 Arrays ................................................................................................................. 6
9.2 Linear Search ...................................................................................................... 6
9.3 Loops (Iteration) .................................................................................................. 6
9.4 Conditional Statements ....................................................................................... 7
9.5 Enums (Direction Control) .................................................................................... 7
9.6 Randomization .................................................................................................... 7
9.7 Simulation and State Management........................................................................ 7
9.8 Arrays as Queues (Conceptually) .......................................................................... 7
9.9 Function Decomposition (Modular Design) ............................................................ 7
10. Source code ........................................................................................................... 8
11. Output ................................................................................................................. 17
1. Introduction
The classic Snake game is a popular arcade-style game where the player controls a
growing snake that must eat food to increase in length while avoiding collisions with walls
and itself. This project is a console-based implementation of the Snake game written in
C++ for the Windows platform, utilizing the Windows Console API for cursor positioning
and colored text output.

The primary goal of this project was to create a playable Snake game that demonstrates
fundamental programming concepts including arrays, control structures, functions, input
handling, and basic game mechanics. The program is also extended and expanded to
provide a longer, detailed implementation suitable for academic projects.

2. Objectives
• Implement a functional Snake game in C++.
• Use arrays to manage the snake's body.
• Use functions to modularize code.
• Implement collision detection with walls and self.
• Use keyboard input to control snake movement.
• Use Windows Console API to enhance user experience with cursor control and
colors.
• Expand code logically to meet project length requirements.

3. Program Overview
3.1 Game Area Setup
• The game runs within a rectangular grid defined by constants WIDTH and HEIGHT.
• The playing field is surrounded by a border drawn using the # character.
• The snake and food appear inside the boundaries of this grid.
3.2 Snake Representation
• The snake’s body is represented by two integer arrays: snakeX[100] and
snakeY[100].
• Each element stores the X and Y coordinates of a segment of the snake’s body.
• snakeLength keeps track of the current number of segments in the snake.

3.3 Food Representation


• The food's location is stored in two variables: foodX and foodY.
• Food is randomly placed on the grid, ensuring it does not appear on the snake.

3.4 Movement and Controls


• The snake moves according to the direction set by the player using W, A, S, D keys.
• The direction is managed by an enum Direction with values LEFT, RIGHT, UP,
DOWN, and STOP.
• Movement is processed in each game loop iteration.
• The game prevents the snake from reversing direction instantly to avoid self-
collision.

3.5 Collision Detection


• The game checks if the snake’s head collides with any wall of the game area.
• It also checks if the snake’s head runs into any other part of its body.
• If a collision occurs, the game ends.

3.6 Growth and Scoring


• When the snake eats food, its length increases by 1.
• The score increases by 10 points per food item eaten.
• New food is placed randomly after each consumption.
3.7 Console Manipulation
• The program uses Windows API functions to control the cursor position
(SetConsoleCursorPosition) for smooth rendering.
• It changes text color with SetConsoleTextAttribute for better visuals.
• The snake’s body segments are drawn in green (color 10), food in red (color 12),
borders in white (color 15), and score in yellow (color 14).

4. Code Structure and Components


The program is modularized into several functions, each handling specific tasks:

• setCursorPosition(int x, int y): Positions the console cursor at (x, y)


coordinates.
• setColor(int color): Changes text color.
• drawBorder(): Draws the game boundary.
• placeFood(): Randomly places food in an empty location.
• drawSnake(): Draws all snake segments.
• eraseTail(int x, int y): Erases the last tail segment to create a moving
effect.
• collision(): Detects collisions with walls and self.
• showScore(): Displays the current score.
• main(): The core function initializes the game, handles input, updates game state,
and manages the game loop.

5. Implementation Details
• Input Handling: Uses _kbhit() and _getch() functions to detect and process
keyboard input without blocking the game loop.
• Game Loop: Runs indefinitely, updating the snake's position, checking collisions,
updating the score, and redrawing game elements.
• Growth Mechanism: Upon eating food, the snake’s length increments, and the
tail's last position is duplicated to visually grow the snake.
• Collision and Game Over: The game immediately ends if a collision is detected.
The player is shown their final score and prompted to exit.
• Performance and Delay: Sleep(speed) controls the refresh rate, enabling
smooth gameplay.

6. Data Structures Used


• Arrays: Used for storing the snake body coordinates.
• Enum: Used for managing direction states.
• Constants: Used for game dimensions and colors.
• Variables: For score, speed, and other game state details.

This project primarily relies on arrays to simulate a queue-like structure where the snake
body shifts positions each frame.

7. Possible Enhancements
• Use dynamic data structures like linked lists for snake body management.
• Add levels or increase speed as score increases.
• Introduce obstacles.
• Implement pause and resume functionality.
• Support arrow keys as input.
• Save high scores in a file.
• Add sound effects.
8. How to Use and Run
• Compile the program in a Windows environment with a C++ compiler (Dev-C++ or
similar).
• Use WASD keys to move the snake.
• Press 'X' to exit the game at any time.
• Avoid colliding with walls or the snake itself.
• Eat food '@' to grow the snake and increase your score.

9. Data Structures and Algorithms (DSA)


Concepts Used
9.1 Arrays
• Used to store the X and Y coordinates of each part of the snake.
• Arrays allow direct access to each body segment of the snake.

9.2 Linear Search


Applied when checking:

• If food overlaps with the snake's body (placeFood()).


• If the snake collides with itself (collision()).
• Simple traversal of array elements to find matches.

9.3 Loops (Iteration)


Used in:

• Drawing game borders and snake body.


• Moving the snake segments.
• Continuously running the main game loop.
• Essential for performing repeated tasks efficiently.

9.4 Conditional Statements


• if, else, and switch statements manage:
o Direction changes.
o Game exit.
o Collision detection.
o Food consumption.

9.5 Enums (Direction Control)


• enum Direction { STOP, LEFT, RIGHT, UP, DOWN } represents direction
states.
• Helps organize and manage directional logic clearly.

9.6 Randomization
• Functions like rand() and srand(time(0)) are used to place food at random
locations.
• Ensures varied gameplay experience by introducing randomness.

9.7 Simulation and State Management


• The snake’s movement, food interaction, and game state are updated frame by
frame.
• Demonstrates real-time state tracking using variables and control logic.

9.8 Arrays as Queues (Conceptually)


• The snake’s movement uses the concept of shifting body segments forward.
• This mimics queue-like behavior where older positions are replaced by newer ones.

9.9 Function Decomposition (Modular Design)


• The program is split into multiple functions like:
o drawSnake(), updateHeadPosition(), checkFood(), etc.
• Enhances readability, reusability, and debugging.

10. Source code


11. Output

You might also like