project
project
PROJECT REPORT
Submitted by
KABISH.M [RA2311030020002]
SURYAA.U [RA2311030020027]
SHREEYAAS.S [RA2311030020053]
Under the guidance of
APRIL 2024
1
SRM INSTITUTE OF SCIENCE AND TECHNOLOGY
(Deemed to be University U/S 3 of UGC Act, 1956)
BONAFIDE CERTIFICATE
Certified that this project report titled SNAKE GAME is the bonafide work of
KABISH.M (RA2311030020002), SURYAA.U (RA2311030020027), and
SHREEYAAS.S (RA2311030020053) who carried out the project work under my
supervision. This project work confirms to 21CSC101T /Object Oriented Design and
Programmig, II Semester, I year, 2024.
SIGNATURE
2
SRM INSTITUTE OF SCIENCE AND TECHNOLOGY
RAMAPURAM, CHENNAI
DECLARATION
We hereby declare that the entire work contained in this project report titled
“SNAKE GAME” has been carried out by KABISH.M (REG NO: RA2311030020002),
Date: SURYAA.U
SHREEYAAS.S
3
ABSTRACT
The provided C++ code implements a simple console-based Snake game, a classic arcade game
where the player controls a snake to eat food and grow in length. The game is designed to run on
a console window, utilizing basic console input/output functions and Windows-specific libraries
for console manipulation and input handling. The game board is represented as a grid with a
fixed width and height, typically 80 columns by 20 rows. The snake, represented by the character
'O', moves around the board, seeking food denoted by '#'. As the snake consumes food, its length
increases, and the player's score goes up. The goal is to eat as much food as possible without
colliding with the walls or the snake's own tail, which would end the game. At the start of the
game, the snake is positioned at the center of the screen, and the initial food location is
randomized within the boundaries. The player's score is initialized to zero, and the game over
flag is set to false. The snake's initial length is one segment, movement direction is stopped. The
main game loop controls the game's flow, continuously updating the game state, rendering the
game board, and processing user input. The rendering function clears the console and redraws
the game board, including the walls, snake, food, and player's score. Snake’s movement is
controlled by the player using the 'WASD' keys, with 'W' for up, 'A' for left, 'S' for down, and 'D'
for right. Pressing 'X' ends the game. The update function moves the snake based on the player's
input direction and checks for collisions with walls, the snake's own tail, and food. If the snake
collides with a wall or its own tail, the game ends. Eating food increases the player's score and
causes the snake to grow longer. The game also includes a function to set the difficulty level,
allowing the player to choose between easy, medium, and hard modes. The difficulty level
affects the speed at which the snake moves across the screen. In easy mode, the snake moves
slowly, making it easier for the player to control. In hard mode, the snake moves quickly,
increasing the difficulty level. Overall, this code provides a basic implementation of the classic
Snake game, demonstrating fundamental concepts such as game loops, user input handling,
collision detection, and rendering in a console-based environment. It serves as a beginner-
friendly example for those interested in learning game development or C++ programming. The
simplicity and clarity of the code make it easy to understand and modify and making it an
excellent starting point for further experimentation.
4
TABLE OF CONTENTS
ABSTRACT 4
LIST OF FIGURES 7
1 INTRODUCTION 8
1.1 OVERVIEW 8
1.3 OBJECTIVE 10
1.4 SCOPE OF THE PROJECT 11
1.5 SUMMARY 12
2.1 OVERVIEW 13
2.2 EXISTING SYSTEM 13
2.3 PROPOSED SYSTEM 14
2.4 SUMMARY 16
3 SYSTEM DESIGN 17
3.1 OVERVIEW 17
3.2 UML DIAGRAMS 18
5
3.3 USE CASE DIAGRAM 19
3.4 CLASS DIAGRAM 20
3.5 SUMMARY 21
4 MODULE IMPLEMENTATION 22
4.1 OVERVIEW 22
4.2 IMPLEMENTATION 24
4.3 CODING 25
4.4 OUTPUT 29
4.5 SUMMARY 32
5 CONCLUSION 34
6 REFERENCES 35
6
LIST OF FIGURES
4.4 OUTPUT 44
7
CHAPTER 1
INTRODUCTION
1.1 OVERVIEW
This C++ program implements a simple console-based version of the classic Snake game. The
game provides a nostalgic gaming experience where the player controls a snake to eat food items
and grow in length. The program utilizes basic console graphics to render the game board and
display game elements such as the snake, food, and score. The game starts by prompting the
player to enter their name and select a difficulty level (easy, medium, or hard). The difficulty
level determines the speed at which the snake moves across the screen. The game board is
represented by ASCII characters, with walls surrounding the playable area and the snake and
food items displayed as specific characters. The player controls the snake's movement using the
arrow keys on the keyboard. The snake moves one unit at a time in the direction specified by the
player. The objective of the game is to eat as much food as possible to score points and grow the
snake's length. The game ends if the snake collides with the walls or with itself. The program
includes functions to initialize the game variables, render the game board, update the game state,
handle user input, and set the game difficulty level. The game board is updated continuously to
reflect the current state of the game, including the position of the snake, the location of the food,
and the player's score. The snake is represented by a series of connected segments, with the head
of the snake denoted by the character 'O' and the body segments denoted by the character 'o'. The
food items are represented by the character '#'. The player's score is displayed at the top of the
screen, along with their name. Overall, this Snake game implementation provides a fun and
challenging gaming experience for players of all ages. It demonstrates fundamental programming
concepts such as user input handling, game logic, and basic graphics rendering in a console
environment. The game's simplicity and addictive gameplay make it a popular choice for casual
gamers and programming enthusiasts alike
8
1.2 PROBLEM STATEMENT
The objective of this project is to develop a console-based Snake game using C++. The game
should provide a classic gaming experience where the player controls a snake to eat food items
and grow in length. The game should be implemented using basic console graphics and should
include features such as setting the game difficulty, displaying the player's score, and handling
user input for controlling the snake's movement. The game should start by prompting the player
to enter their name and select a difficulty level (easy, medium, or hard). The difficulty level
should determine the speed at which the snake moves across the screen. The game board should
be represented by ASCII characters, with walls surrounding the playable area and the snake and
food items displayed as specific characters. The player should control the snake's movement
using the arrow keys on the keyboard. The snake should move one unit at a time in the direction
specified by the player. The objective of the game should be to eat as much food as possible to
score points and grow the snake's length. The game should end if the snake collides with the
walls or with itself. The program should include functions to initialize the game variables, render
the game board, update the game state, handle user input, and set the game difficulty level. The
game board should be updated continuously to reflect the current state of the game, including the
position of the snake, the location of the food, and the player's score. The snake should be
represented by a series of connected segments, with the head of the snake denoted by the
character 'O' and the body segments denoted by the character 'o'. The food items should be
represented by the character '#'. The player's score should be displayed at the top of the screen,
along with their name. Overall, the Snake game should provide a fun and challenging gaming
experience for players of all ages. It should demonstrate fundamental programming concepts
such as user input handling, game logic, and basic graphics rendering in a console environment.
The game's simplicity and addictive gameplay should make it a popular choice for casual gamers
and programming enthusiasts alike.
9
1.3 OBJECTIVE
The objective of this C++ program is to implement a console-based Snake game that provides an
interactive and engaging gaming experience. The game aims to recreate the classic gameplay of
the original Snake game, where the player controls a snake to eat food and grow in length while
avoiding collisions with walls and its own tail. The program is designed to showcase
fundamental concepts of C++ programming, including object-oriented design, user input
handling, game logic implementation, and basic console graphics rendering. The primary goal of
the program is to create a functional and enjoyable game that demonstrates proficiency in C++
programming. By developing the Snake game, the programmer aims to improve their
understanding and application of key programming concepts such as classes, objects, inheritance,
and encapsulation. Additionally, the program serves as a practical exercise to enhance problem-
solving skills and logical thinking in the context of game development. Another objective of the
program is to provide a customizable gaming experience for players. The program allows players
to set the game difficulty level, choosing between easy, medium, or hard modes. This feature
adds replay value to the game, as players can adjust the game's challenge level to suit their
preferences and skill level. Implementing different difficulty levels also demonstrates the ability
to incorporate user preferences and settings into the game design. Furthermore, the program aims
to showcase effective game design principles, including clear and concise user interfaces,
intuitive controls, and responsive gameplay. By following these principles, the program enhances
the overall user experience and ensures that the game is enjoyable and accessible to a wide
audience. Overall, the objective of this C++ program is to create a high-quality Snake game that
is both entertaining and educational. By implementing core programming concepts in the context
of game development, the program aims to provide a valuable learning experience for aspiring
programmers and game developers. Through this project, the programmer seeks to improve their
programming skills, enhance their understanding of game development principles, and create a
fun and engaging game for players to enjoy.
10
1.4 SCOPE OF THE PROJECT
The scope of this C++ project includes the development of a console-based Snake game that
provides a classic gaming experience for players. The project encompasses various aspects of
game development, including game design, programming, testing, and documentation. The
project scope is defined by the following key components:
1. Game Design: The project involves designing the game mechanics, including the snake's
movement, food generation, collision detection, and scoring system. The game design should be
intuitive and engaging, providing players with a challenging yet enjoyable experience.
2. Programming: The project requires implementing the game logic in C++, including functions
for initializing the game, rendering the game board, updating the game state, handling user input,
and setting the game difficulty. The programming should be well-structured and efficient,
demonstrating proficiency in C++ coding practices.
3. User Interface: The project includes designing the user interface for the game, including
displaying the game board, the snake, food items, and the player's score. The user interface
should be clear, easy to understand, and visually appealing, enhancing the overall gaming
experience.
4. Testing: The project involves testing the game to ensure that it functions correctly and is free
of bugs and errors. Testing should include unit testing of individual functions, as well as
gameplay testing to verify that the game behaves as expected under various conditions.
5. Documentation: The project requires documenting the code to explain its functionality,
structure, and usage. Documentation should also include instructions for compiling and running
the game, as well as any additional information that may be useful for users or developers.
6. Future Enhancements: The project scope may include considerations for future enhancements
to the game, such as adding new features, improving graphics, or optimizing performance.
Future enhancements should be planned to ensure compatibility with the existing codebase and
11
overall game design.
Overall, the scope of this project is to develop a functional and enjoyable Snake game using C+
+ that demonstrates proficiency in programming concepts and game development principles. The
project aims to create a high-quality game that provides a satisfying gaming experience for
players while showcasing the programmer's skills and creativity in game
1.5 SUMMARY
The Snake game implemented in C++ offers a classic and engaging gaming experience,
showcasing fundamental programming concepts and game development principles. The project
demonstrates proficiency in C++ programming, including the use of classes, objects, enums, and
basic console graphics. By designing and implementing the game, the programmer has gained
valuable experience in problem-solving, algorithm development, and software design. The
game's modular structure allows for easy understanding and maintenance of the code. Each
module serves a specific purpose, such as initializing the game, rendering the game board,
updating the game state, handling user input, and setting the game difficulty. This modular
approach enhances code readability and makes it easier to add new features or modify existing
ones in the future. One of the key features of the game is its ability to set the difficulty level,
allowing players to adjust the game's speed and challenge. This feature adds replay value to the
game, as players can continue to challenge themselves and improve their skills. Additionally, the
game's use of random food generation and tail management adds complexity and strategy to the
gameplay, making it more dynamic and engaging. The game's user interface is simple yet
effective, using ASCII characters to represent the game elements. While the graphics are basic,
they serve their purpose well and provide a nostalgic feel reminiscent of early arcade games. The
inclusion of the player's name and score adds a personal touch to the game, making it more
immersive for the player. Overall, the Snake game project demonstrates the programmer's ability
to apply programming concepts to create a functional and enjoyable game. It showcases essential
skills such as problem-solving, algorithm design, and code optimization. The project also
highlights the importance of user experience and game design principles in creating a successful
game. Moving forward, there are several potential areas for improvement and expansion. Adding
sound effects, music, and more advanced graphics could enhance the game's appeal and
immersion. Implementing additional features such as power-ups, obstacles, and multiplayer
modes could further enhance the game's depth and replayability. Overall, the Snake game project
12
serves as a solid foundation for future game development projects, providing a strong framework
for building more complex and engaging games in the future
CHAPTER 2
ANALYSIS AND SYSTEM REQUIREMENTS
2.1 OVERVIEW
This C++ program implements a simple console-based version of the classic Snake game. The
game provides a nostalgic gaming experience where the player controls a snake to eat food items
and grow in length. The program utilizes basic console graphics to render the game board and
display game elements such as the snake, food, and score. The game starts by prompting the
player to enter their name and select a difficulty level (easy, medium, or hard). The difficulty
level determines the speed at which the snake moves across the screen. The game board is
represented by ASCII characters, with walls surrounding the playable area and the snake and
food items displayed as specific characters. The player controls the snake's movement using the
arrow keys on the keyboard. The snake moves one unit at a time in the direction specified by the
player. The objective of the game is to eat as much food as possible to score points and grow the
snake's length. The game ends if the snake collides with the walls or with itself. The program
includes functions to initialize the game variables, render the game board, update the game state,
handle user input, and set the game difficulty level. The game board is updated continuously to
reflect the current state of the game, including the position of the snake, the location of the food,
and the player's score. The snake is represented by a series of connected segments, with the head
of the snake denoted by the character 'O' and the body segments denoted by the character 'o'. The
food items are represented by the character '#'. The player's score is displayed at the top of the
screen, along with their name. Overall, this Snake game implementation provides a fun and
challenging gaming experience for players of all ages. It demonstrates fundamental programming
concepts such as user input handling, game logic, and basic graphics rendering in a console
environment. The game's simplicity and addictive gameplay make it a popular choice for casual
gamers and programming enthusiasts alike
13
The existing system for the Snake game typically involves implementations in various
programming languages, including C++, Python, Java, and others. These implementations are
often designed for different platforms, such as desktop, mobile, or web, and may vary in
complexity and features. The key components of the existing system for the Snake game include:
1. Game Mechanics: The basic mechanics of the Snake game involve controlling a snake to eat
food items and grow in length. The snake moves in a specified direction, and the player must
avoid colliding with walls or the snake's own body. Eating food increases the snake's length and
score.
2. User Interface: The user interface of the Snake game typically includes a game board where
the snake moves, food items, and the player's score. The user interface may also include
additional elements such as a game menu, settings, and high score display.
3. Game Logic: The game logic of the Snake game includes functions for initializing the game,
rendering the game board, updating the game state, handling user input, and determining game
over conditions. The game logic ensures that the game behaves correctly and responds to player
actions.
4. Graphics: The graphics of the Snake game are usually simple and use basic shapes or ASCII
characters to represent the snake, food items, and game elements. The graphics are designed to
be easy to understand and visually appealing.
5. Difficulty Levels: Many implementations of the Snake game include multiple difficulty levels,
allowing players to adjust the speed of the snake and the complexity of the game. Higher
difficulty levels increase the challenge for players.
6. Platforms: The Snake game is available on a wide range of platforms, including desktop
computers, mobile devices, and web browsers. Each platform may have its implementation
optimized for the specific platform's capabilities and requirements.
7. Multiplayer Support: Some implementations of the Snake game include multiplayer support,
allowing multiple players to compete against each other or play cooperatively.
8. High Scores: The Snake game often includes a high score feature that allows players to track
their best scores and compete with others for the top score.
Overall, the existing system for the Snake game provides a simple yet entertaining gaming
experience that has remained popular since its inception. The game's straightforward mechanics
and addictive gameplay make it a classic choice for gamers of all ages.
14
The proposed system for the Snake game aims to enhance the existing game implementation by
adding new features and improvements to make the game more engaging and enjoyable for
players. The key components of the proposed system include:
1. Enhanced Graphics: The proposed system will include improved graphics to enhance the
visual appeal of the game. This could involve using more detailed graphics for the snake, food
items, and game elements, as well as adding animations and effects to make the game more
dynamic.
2. Sound Effects and Music: The proposed system will incorporate sound effects and background
music to enhance the gaming experience. Sound effects will be used for actions such as snake
movement, eating food, and colliding with obstacles. Background music will help create a more
immersive atmosphere for the game.
3. Power-Ups and Special Items: The proposed system will introduce power-ups and special
items that can appear randomly on the game board. These items will provide temporary benefits
to the player, such as increasing the snake's speed, making the snake invincible, or doubling the
score for a limited time.
4. Advanced AI for Computer-Controlled Snake: The proposed system will include an option for
a computer-controlled snake that uses advanced artificial intelligence (AI) algorithms to move
and behave like a human player. This will add an additional challenge for players who want to
compete against a more challenging opponent.
5. Multiplayer Mode: The proposed system will introduce a multiplayer mode that allows players
to compete against each other online. Players will be able to join games with friends or compete
against random opponents from around the world, adding a competitive element to the game. 6.
Customization Options: The proposed system will include customization options that allow
players to personalize their gaming experience. Players will be able to customize the appearance
of their snake, choose different game board themes, and adjust game settings to suit their
preferences.
7. Achievements and Leaderboards: The proposed system will include an achievements system
that rewards players for completing specific challenges or reaching certain milestones in the
game. Additionally, the game will feature online leaderboards where players can compare their
scores with others and compete for the top spot.
Overall, the proposed system for the Snake game aims to take the classic gameplay of the 12
original game and enhance it with new features, improved graphics, and advanced gameplay
elements. The goal is to create a more immersive and enjoyable gaming experience that appeals
15
to both new and existing players.
2.4 SUMMARY
The Snake game implemented in C++ offers a classic and engaging gaming experience,
showcasing fundamental programming concepts and game development principles. The project
demonstrates proficiency in C++ programming, including the use of classes, objects, enums, and
basic console graphics. By designing and implementing the game, the programmer has gained
valuable experience in problem-solving, algorithm development, and software design. The
game's modular structure allows for easy understanding and maintenance of the code. Each
module serves a specific purpose, such as initializing the game, rendering the game board,
updating the game state, handling user input, and setting the game difficulty. This modular
approach enhances code readability and makes it easier to add new features or modify existing
ones in the future. One of the key features of the game is its ability to set the difficulty level,
allowing players to adjust the game's speed and challenge. This feature adds replay value to the
game, as players can continue to challenge themselves and improve their skills. Additionally, the
game's use of random food generation and tail management adds complexity and strategy to the
gameplay, making it more dynamic and engaging. The game's user interface is simple yet
effective, using ASCII characters to represent the game elements. While the graphics are basic,
they serve their purpose well and provide a nostalgic feel reminiscent of early arcade games. The
inclusion of the player's name and score adds a personal touch to the game, making it more
immersive for the player. Overall, the Snake game project demonstrates the programmer's ability
to apply programming concepts to create a functional and enjoyable game. It showcases essential
skills such as problem-solving, algorithm design, and code optimization. The project also
highlights the importance of user experience and game design principles in creating a successful
game. Moving forward, there are several potential areas for improvement and expansion. Adding
sound effects, music, and more advanced graphics could enhance the game's appeal and
immersion. Implementing additional features such as power-ups, obstacles, and multiplayer
modes could further enhance the game's depth and replayability. Overall, the Snake game project
16
serves as a solid foundation for future game development projects, providing a strong framework
for building more complex and engaging games in the future
CHAPTER 3
SYSTEM DESIGN
3.1 OVERVIEW
The UML diagrams for the Online Movie Ticket System provide an in-depth and comprehensive
overview of its multifaceted functionality, intricate interactions, intricate workflows, and
sophisticated data model. The Use Case Diagram serves as a cornerstone, illustrating the myriad
interactions between diverse users and the system, meticulously identifying actors such as
customers and administrators, delineating their varied actions ranging from browsing movies to
managing user accounts. In parallel, the Sequence Diagram orchestrates the system's dynamic
narrative, meticulously mapping the chronological order of interactions, elucidating how
messages seamlessly flow between actors, objects, and components during critical use cases such
as ticket booking.
Furthermore, the Activity Diagram intricately unfolds the intricate workflow within the system,
meticulously outlining the myriad steps entailed in pivotal processes like booking a movie ticket,
encapsulating decision points, loops, and concurrency. Meanwhile, the Class Diagram stands as
the bedrock, unfurling the static structure of the system with precision and clarity, meticulously
detailing the plethora of classes such as Movie, User, Ticket, and Theater, meticulously
elucidating their attributes, methods, and intricate relationships. Collectively, these UML
diagrams constitute invaluable tools, empowering system designers, developers, and stakeholders
with profound insights, fostering seamless communication, and facilitating meticulous
documentation throughout the entire development lifecycle.
17
3.2 UML DIAGRAMS
UML is not a programming language, it is rather a visual language. We use UML diagrams to
portray the behaviour and structure of a system. UML helps software engineers, businessmen
and system architects with modelling, design and analysis. UML is linked with object oriented
design and analysis. UML makes the use of elements and forms associations between them to
form diagrams.
In UML, use-case diagrams model the behaviour of a system and help to capture the
requirements
of the system. These diagrams also identify the interactions between the system and its actors.
The use cases and actors in use-case diagrams describe what the system does and how the actors
use it, but not how the system operates internally.
In UML, Class diagram is a static diagram. It represents the static view of an application. Class
diagram is not only used for visualizing, describing, and documenting different aspects of a
system but also for constructing executable code of the software application. A class represent a
concept which encapsulates state (attributes) and behaviour (operations). Each attribute has a
type. Each operation has a signature. The class name is the only mandatory information.
In UML, Activity diagram visually presents a series of actions or flow of control in a system
similar to flowchart or a data flow diagram. This diagram can also show concurrent processes
and decision points, making it highly effective for visualizing the workflow or operational logic
of a system. These often used in business process modelling.
18
In UML, Sequence diagram shows process interactions arranged in time sequence in the field of
software engineering. It depicts the processes involved and the sequence of messages exchanged
between the processes. These diagram illustrates the sequence of messages between the objects
in an interaction in sequential order.
20
3.5 SUMMARY
The UML diagrams for the snake game serve as a comprehensive and intricate roadmap,
providing a detailed understanding of the system's architecture, functionality, and interactions.
The Use Case Diagram acts as a cornerstone, delineating the myriad actions that users can
undertake within the system. Concurrently, the Sequence Diagram intricately weaves the
dynamic narrative of the system, meticulously capturing the chronological order of interactions
between objects during specific use cases, elucidating the intricate flow of messages and system
behavior. Moreover, the Activity Diagram unfurls the elaborate workflow within the system,
meticulously outlining the intricate steps involved in pivotal processes encapsulating decision
points, loops, and concurrency with precision. Meanwhile, the Class Diagram stands as the
bedrock of the system's static structure, meticulously detailing the myriad classes their attributes,
methods, and intricate relationships, providing a foundational understanding of the system's
underlying data model. These UML diagrams offer a rich and nuanced perspective into the
design, functionality, and architecture of the snake game, serving as invaluable tools for system
comprehension, communication, and development throughout the entire software lifecycle.
21
CHAPTER 4
MODULE IMPLEMENTATION
4.1 OVERVIEW
This C++ program implements a classic snake game in a console environment, providing an
interactive and entertaining experience for players. The program's functionality is divided into
several key components, each responsible for a specific aspect of the game. The inclusion of
necessary header files, such as `<conio.h>`, `<iostream>`, and `<windows.h>`, ensures that the
program can handle console input/output and utilize Windows-specific functions like `Sleep()`
for controlling game speed.
Global variables play a crucial role in maintaining the game state. These variables include the
dimensions of the game board (`width` and `height`), the coordinates of the snake's head (`x` and
`y`), the coordinates of the food (`fruitCordX` and `fruitCordY`), the player's score
(`playerScore`), an array to store the coordinates of the snake's tail (`snakeTailX` and
`snakeTailY`), the length of the snake's tail (`snakeTailLen`), the current direction of the snake
(`sDir`), and a boolean variable to determine if the game is over (`isGameOver`).
The `GameInit()` function is responsible for initializing these variables at the start of the game. It
sets `isGameOver` to false, `sDir` to STOP (0), places the snake's head in the center of the board,
generates random coordinates for the food, and sets the player's score to 0. This function ensures
that the game starts with a clean slate and all necessary variables are properly initialized.
The `GameRender()` function is crucial for rendering the game board on the console screen. It
uses loops to iterate through each cell of the game board, printing the walls, the snake's head, the
food, and the tail based on their respective coordinates. This function ensures that the game is
22
visually appealing and that the player can easily see the game elements and their positions.
The `UpdateGame()` function is responsible for updating the game state based on the player's
input and the current state of the game. It moves the snake's head according to the current
direction (`sDir`), updates the positions of the snake's tail segments, and checks for collisions
with walls, the snake's tail, and the food. If the snake collides with the food, the player's score is
increased, and the snake grows longer.
Additionally, the program includes a `SetDifficulty()` function that allows the player to set the
game's difficulty level. The player can choose between Easy, Medium, and Hard levels, which
determine the speed of the game. This function adds an element of customization to the game,
allowing players to adjust the game's difficulty to their liking.
User input is handled by the `UserInput()` function, which checks if a key is pressed and updates
the direction of the snake (`sDir`) accordingly. The player can control the snake's movement
using the arrow keys, changing its direction to navigate the game board and collect food.
Finally, the `main()` function serves as the entry point of the program. It prompts the player to
enter their name, sets the game's difficulty level, initializes the game using `GameInit()`, and
enters a game loop. The game loop continuously renders the game board, handles user input,
updates the game state, and checks if the game is over. If the game is over, the loop exits, and the
program ends.
23
4.2 IMPLEMENTATION
When implementing a snake game, breaking down the development into distinct modules can
simplify the process, enhance maintainability, and make future updates easier. The module
description for snake game is:
1. Header Files: The program includes necessary header files such as `<conio.h>` for
console input/output functions, `<iostream>` for standard input/output streams, and
`<windows.h>` for using Windows-specific functions like `Sleep()`.
2. Global Variables: Global variables are declared to store the game's state, including the
width and height of the game board, coordinates for the snake's head and food, player
score, snake's tail coordinates, length of the tail, current direction of the snake (`sDir`),
and a boolean variable to check if the game is over.
3. Game Initialization (`GameInit()`): This function initializes the game variables. It sets the
game over status to false, the direction of the snake to STOP (0), places the snake's head
in the center of the board, generates random coordinates for the food, and sets the player's
score to 0.
4. Game Rendering (`GameRender()`): This function renders the game board on the
console. It clears the console and iterates through each cell of the board, printing the
walls, snake's head, food, and tail based on their respective coordinates.
5. Game State Update (`UpdateGame()`): This function updates the game state based on the
player's input and current game state. It moves the snake's head according to the
direction, updates the tail's position, checks for collisions with walls, tail, and food, and
updates the player's score accordingly.
6. Difficulty Level Setting (`SetDifficulty()`): This function allows the player to set the
game's difficulty level by choosing between Easy, Medium, and Hard. The chosen
difficulty level determines the speed of the game.
7. User Input Handling (`UserInput()`): This function handles user input to change the
direction of the snake. It checks if a key is pressed and updates the direction accordingly
(LEFT, RIGHT, UP, DOWN), or ends the game if 'x' key is pressed.
8. Main Function and Game Looping: The `main()` function is the entry point of the
24
program. It prompts the player to enter their name, sets the game difficulty, initializes the
game, and enters a game loop. The game loop renders the game, handles user input,
updates the game state, and repeats until the game is over.
4.3 CODING
switch (sDir) {
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
}
GameInit();
while (!isGameOver) {
GameRender(playerName);
UserInput();
UpdateGame();
// creating a delay for according to the chosen
// difficulty
Sleep(dfc);
}
return 0;
}
OUTPUT
Figure 4.1 Entering the Player’s Name and Choosing the Difficulty
29
Figure 4.2 Initial State of the Game
Figure 4.3 Game Termination When Snake Collides with the Wall
30
Figure 4.4 Game Termination when Snake Collides with its Own Tail
31
4.5 SUMMARY
This C++ program is a simple console-based snake game that allows players to control a snake to
eat food and grow longer while avoiding collisions with walls and its own tail. Here's a summary
of the code:
1. Header Files: The program includes three header files: `<conio.h>` for console input/output
functions, `<iostream>` for standard input/output streams, and `<windows.h>` for using
Windows-specific functions like `Sleep()`.
2. Global Variables: Several global variables are declared at the beginning of the program. These
include the width and height of the game board, coordinates for the snake's head (`x` and `y`),
coordinates for the food (`fruitCordX` and `fruitCordY`), the player's score (`playerScore`), an
array to store the coordinates of the snake's tail, the length of the snake's tail (`snakeTailLen`), a
variable to store the direction of the snake (`sDir`), and a boolean variable to check if the game is
over (`isGameOver`).
3. GameInit(): This function initializes the game variables. It sets `isGameOver` to false, `sDir`
to STOP (0), places the snake's head in the center of the board (`x = width / 2`, `y = height / 2`),
generates random coordinates for the food, and sets the player's score to 0.
4. GameRender(): This function renders the game board on the console. It clears the console
(`system("cls")`) and then iterates through each row and column of the board. It prints the top
and bottom walls with '-', the side walls with '|', the snake's head with 'O', the food with '#', and
the snake's tail with 'o'. It also displays the player's score.
5. UpdateGame(): This function updates the game state based on the player's input and the
current state of the game. It moves the snake's head based on the direction (`sDir`) and updates
the positions of the snake's tail segments. It checks for collisions with walls, the snake's tail, and
the food, updating the game state accordingly.
6. SetDifficulty():This function allows the player to set the game difficulty level. It prompts the
player to choose between Easy, Medium, and Hard. The difficulty level determines the speed of
the game by setting a delay (`dfc`) using the `Sleep()` function.
32
7. UserInput(): This function handles user input to change the direction of the snake. It checks if
a key is pressed (`_kbhit()`) and then gets the pressed key (`_getch()`) to update the direction
(`sDir`) accordingly.
8. Main(): The `main()` function is the entry point of the program. It prompts the player to enter
their name, sets the game difficulty, initializes the game, and enters a game loop. The game loop
renders the game, handles user input, updates the game state, and repeats until the game is over.
In summary, this program demonstrates basic concepts of game development in C++, including
game initialization, rendering, user input handling, game state updating, and game looping. It
provides a simple yet entertaining gameplay experience for the player.
CHAPTER 5
33
CONCLUSION
In conclusion, the project has been developed successfully, and the system's performance has
been thoroughly evaluated and found to be highly satisfactory. This robust interface significantly
enhances the customer experience by providing immediate access to information about currently
running movies and allows for quick and easy seat reservation. This good experince for users
who wish to play a good game. The system also boasts a user-friendly interface, which simplifies
the process for theater staff to update and manage movie information efficiently. This feature is
especially beneficial in keeping the scores to date thereby ensuring that user receive accurate
information. The report effectively illustrates the seamless process for user to select their
difficulty level. This flow demonstrates the streamlined, intuitive nature of the user interface,
which contributes significantly to user satisfaction and ease of use. Furthermore, Overall, these
features collectively enhance the overall gamers, making it more enjoyable and accessible for all
users. The system's ability to integrate advanced functionalities with user-centered design
principles stands as a testament to the project's success, setting a new standard for other gaming
platform.
34
REFERENCES
1.GeeksforGeeks
2.Programiz
3.Youtube
4.Google.com
35