0% found this document useful (0 votes)
38 views53 pages

Data Case Report

The document describes a C++ implementation of the classic Snake game using the SDL and TTF libraries. It analyzes the system architecture, game mechanics, programming practices, and integration of SDL/TTF. While serving as an educational tool, it could be improved with additional comments, documentation, customization options, and more advanced features to provide a deeper learning experience.

Uploaded by

sidharthbabu321
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)
38 views53 pages

Data Case Report

The document describes a C++ implementation of the classic Snake game using the SDL and TTF libraries. It analyzes the system architecture, game mechanics, programming practices, and integration of SDL/TTF. While serving as an educational tool, it could be improved with additional comments, documentation, customization options, and more advanced features to provide a deeper learning experience.

Uploaded by

sidharthbabu321
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/ 53

CASE STUDY REPORT

ON

SNAKE GAME

BY

JASMIN.J (811221068)

Submitted in partial fulfillment of the

Requirements for the award M.Sc (Computer Science) degree of

University of Kerala 2022-2023

SCHOOL OF DISTANCE EDUCATION

UNIVERSITY OF KERALA

KARIYAVATTOM

Page 1
DECLARATION

I hereby declare that the work presented in the case study titled “SNAKE
GAME” is on the original work done by us under the guidance of Mrs. Liji I.H, HOD of
Computer Science department. The same work has not been submitted elsewhere or any other
degree.

JASMIN.J (811221068)

Page 2
SCHOOL OF DISTANCE EDUCATION

UNIVERSITY OF KERALA

KARIYAVATTOM

CERTIFICATE

This is to certify that the project report entitled “SNAKE GAME” submitted
to School of Distance Education, University of Kerala in partial fulfillment of the
requirement for the award of the Degree of MASTER OF COMPUTER SCIENCE, is an
authentic and original work carried out by JASMIN.J(811221068).

External Examiner1

Lecturer in charge

External Examiner2

Page 3
ACKNOWLEDGEMENT

We gratefully acknowledge the support and kind hearted cooperation by Mrs.


Liji I.H, HOD of Computer Science department. We extend our heartfelt thanks to our
classmates, friends and well wishers, who helped us to make this case study success. Above
all we are thankful to God, almighty for the strength and presence of mind to complete these
studies work successfully, we humbly solicit and almighty’s blessings. Our sincere thanks
and apologies to anyone who deserve the credit but whose names fail to appear in the list
above.

JASMIN.J (811221068)

Page 4
ABSTRACT

The Snake game implementation is a dynamic and educational project that combines
C++ programming with the Simple DirectMedia Layer (SDL) and TrueType Font (TTF)
libraries to create a classic gaming experience. The project not only delivers an engaging
Snake game but also serves as a valuable learning resource for individuals exploring game
development and programming concepts. With a modular and object-oriented design, the
codebase emphasizes code maintainability and reusability, providing a solid foundation for
future enhancements. The integration of SDL ensures robust graphical rendering, while the
TTF library enhances text representation, contributing to a polished user interface.
Educational features, including inline comments, comprehensive documentation, and a
tutorial mode, guide learners through the codebase, offering insights into C++ programming
and game development principles. The project's commitment to regular system maintenance
ensures its adaptability and relevance, making it a sustainable and evolving resource. In
summary, the Snake game implementation successfully marries entertainment with
education, creating a well-crafted project that caters to both gaming enthusiasts and learners
in the programming community.

Page 5
TABLE OF CONTENTS

1. INTRODUCTION 7

2. SYSTEM ANALYSIS 8

2.1 EXISTING SYSTEM 10

2.2 PROPOSED SYSTEM 11

3. SYSTEM SPECIFICATION 13

3.1 HARDWARE SPECIFICATION 14

3.2 SOFTWARE SPECIFICATION 15

3.3 DEVELOPING TOOLS 16

4. SYSTEM DESIGN 19

4.1 INPUT DESIGN 21

4.2 OUTPUT DESIGN 23

5. SYSTEM TESTING 26

5.1 TESTING OBJECTIVES 27

5.2 TYPES OF TESTING 29

6. SYSTEM IMPLEMENTATION 31

6.1 IMPLEMENTATION 32

6.2 TRAINING 33

7. SYSYTEM MAINTENANCE 34

8. CONCLUSION 36

9. FUTURE ENHANCEMENT 37

10. BIBLIOGRAPHY 39

APPENDIX

Screenshots

Source cod

Page 6
1. INTRODUCTION

This code represents a simple yet engaging implementation of the classic Snake game
in C++ using the SDL (Simple DirectMedia Layer) library. The purpose of this program is to
provide a hands-on demonstration of basic game development concepts, including graphics
rendering, user input handling, collision detection, and dynamic memory management.

The code begins with necessary header and library includes, setting the stage for utilizing
SDL and TTF for graphics and text rendering. Constants and global variables are declared,
outlining essential parameters such as screen dimensions, grid size, and game state indicators.

A key component is the SnakeSegment structure, representing each segment of the snake.
The Init function initializes SDL, TTF, and creates the game window and renderer. The
snake's initial segment is positioned at the center of the screen.

The game mechanics include functions for generating food, moving the snake, and checking
for collisions with walls and its own body. User input through arrow keys dynamically
changes the snake's direction, influencing its movement.

The rendering functions (DrawSnake, DrawFood, DrawScore, DrawGameOver) utilize SDL


to visually represent the game elements on the screen. The DrawScore function incorporates
TTF to display the player's score. The main loop continuously updates the game state,
handles user input, and renders the graphics, providing an interactive and visually appealing
experience.

The code concludes with a cleanup section, deallocating memory and resources to ensure a
clean exit. This Snake game serves as an educational tool, offering insights into SDL-based
game development for beginners. Its simplicity makes it an ideal starting point for those
looking to grasp fundamental concepts before delving into more complex game projects.
Overall, this code provides a foundation for understanding game development principles in a
fun and accessible manner.

Page 7
2. SYSTEM ANALYSIS

This Snake game implementation in C++ using the SDL library can be analyzed from various
perspectives, including system architecture, game mechanics, and programming practices.

System Architecture:

The code exhibits a straight-forward system architecture, following a procedural


paradigm. The main components include initialization routines (Init), game logic (movement,
collision detection), rendering functions (DrawSnake, DrawFood, DrawScore,
DrawGameOver), and cleanup procedures. The use of global variables and simple function
calls contributes to the code's readability but may pose challenges in larger projects. The
structuring of the Snake game as a sequence of discrete functions facilitates understanding
and modification.

Game Mechanics:

The core game mechanics are well-implemented. The snake's movement, controlled
by user input, is smooth and responsive. Collision detection is effective, encompassing
checks for wall collisions and self-intersections. The incorporation of a linked list to represent
the snake's body allows for dynamic growth as it consumes food. However, further
enhancements, such as additional game features (e.g., levels, obstacles) and a more
sophisticated scoring system, could elevate the gameplay experience.

Programming Practices:

The code adheres to good programming practices by encapsulating functionality


within functions and utilizing constants for parameters. The use of a linked list for the snake
segments demonstrates an understanding of data structures. However, there is room for
improvement in terms of encapsulation and modularity. For instance, encapsulating game-
related variables and functions within a class could enhance code organization and
maintainability. Additionally, error handling is somewhat limited, and the code could benefit
from more robust mechanisms for handling unexpected scenarios.

Page 8
SDL and TTF Integration:

The code effectively leverages the SDL library for graphics rendering and TTF for
text rendering. The integration of fonts for displaying the score and the "Game Over"
message demonstrates an understanding of multimedia library usage. The choice of font and
color schemes aligns with the game's aesthetics. However, providing options for
customization or supporting different screen resolutions could enhance the code's
adaptability.

Room for Improvement:

While this Snake game code serves its educational purpose well, there are areas for
improvement. The introduction of comments and documentation could enhance code
readability and aid learners in understanding the logic. Additionally, the incorporation of
more advanced SDL features, such as event-driven programming or sprite animations, could
expand the code's educational value and provide a deeper dive into game development
concepts.

In summary, this Snake game implementation serves as a commendable educational resource


for individuals learning C++ and game development with SDL. It provides a solid foundation
for understanding fundamental concepts and can be further extended and refined to
encompass more advanced game development practices.

Page 9
2.1 EXISTING SYSTEM

The existing system represents a classic implementation of the Snake game in C++
using the SDL library, emphasizing simplicity and educational value. The system architecture
centers around procedural programming, with distinct functions handling initialization, game
logic, rendering, and cleanup. The global variables, while aiding in code readability for this
relatively small-scale project, might pose challenges in larger applications and could benefit
from encapsulation within a class for improved modularity.

The core game mechanics are robust, featuring responsive user input for snake
movement and effective collision detection, including checks for wall collisions and self-
intersections. The use of a linked list to represent the snake's body allows for dynamic growth
as it consumes food. However, the simplicity of the current mechanics leaves room for
further expansion. Introducing additional game features, such as multiple levels, obstacles, or
power-ups, could enhance the gameplay experience and provide learners with a deeper
understanding of game development concepts.

The code adheres to good programming practices by encapsulating functionality


within functions and using constants for parameters. The integration of SDL for graphics
rendering and TTF for text rendering demonstrates an understanding of multimedia library
usage. The incorporation of fonts for displaying the score and the "Game Over" message
aligns with the game's aesthetics. However, there is an opportunity to improve error handling
mechanisms and introduce comments or documentation to facilitate comprehension,
especially for those new to C++ or game development.

While the existing system effectively achieves its educational goal by providing a
clear and accessible example of a simple game, there are areas for refinement. Introducing
comments and documentation could enhance code readability and aid learners in
understanding the logic. Moreover, expanding the system to incorporate more advanced SDL
features or game development concepts, such as state machines or modular design patterns,
could elevate the educational value of the code and prepare learners for more complex
projects.

Page 10
In conclusion, the existing Snake game implementation serves as a commendable
starting point for individuals learning C++ and game development with SDL. It successfully
conveys fundamental concepts and can be further developed to encompass more advanced
game development practices, providing learners with a solid foundation and encouraging
exploration of additional features and optimizations.

2.2 PROPOSED SYSTEM

The proposed system builds upon the existing Snake game implementation, aiming to
enhance its features, user experience, and educational value. The system architecture will
undergo a transformation to adopt a more modular and object-oriented design, encapsulating
related functionalities within classes. This design choice contributes to improved code
organization, maintainability, and scalability, facilitating the potential addition of new
features and game elements.

One major proposed enhancement involves the introduction of a menu system. This
addition will provide users with options to start a new game, adjust settings (such as difficulty
levels or visual themes), view high scores, and exit the game. Implementing a menu system
requires handling user input differently, introducing new SDL event handling mechanisms
and enhancing the graphical user interface. This modification not only enriches the gameplay
experience but also provides learners with insights into event-driven programming and user
interface design.

To further engage users and elevate the gaming experience, the proposed system
includes the implementation of sound effects and background music using SDL's audio
capabilities. This addition not only enhances the sensory experience but also provides an
opportunity for learners to delve into multimedia integration within game development. The
system will support various audio cues, such as snake movement, eating food, and collision
events, contributing to a more immersive and polished gaming experience.

In terms of gameplay dynamics, the proposed system introduces progressive difficulty


levels. As players achieve higher scores or reach specific milestones, the game's speed
increases, presenting a greater challenge. This enhancement requires adjustments to the
movement and update mechanisms, providing learners with exposure to adaptive game
difficulty algorithms and reinforcing their understanding of game pacing and progression.

Page 11
Educational enhancements are incorporated through the introduction of inline comments and
comprehensive documentation. This ensures that learners, particularly those new to C++ or
game development, can easily understand the code's logic and structure. Additionally, the
proposed system includes a tutorial mode that guides users through the codebase, explaining
key concepts, algorithms, and design decisions. This approach fosters a deeper understanding
of game development principles and encourages learners to explore and modify the code
confidently.

In conclusion, the proposed system seeks to evolve the existing Snake game into a
more feature-rich and educational experience. By embracing modular design, introducing
new gameplay elements, incorporating multimedia features, and enhancing educational
support, the proposed system aims to provide learners with a comprehensive and engaging
introduction to game development while offering a versatile foundation for further
exploration and experimentation.

Page 12
3. SYSTEM SPECIFICATION

The system specification for this Snake game implementation outlines a


comprehensive plan that encompasses both functional and non-functional requirements,
providing a detailed roadmap for the development and enhancement of the project.

Functional Requirements:

The specification begins with the delineation of functional requirements, identifying


the core features and behaviours that the system is expected to exhibit. This includes detailed
specifications for user input handling, game mechanics, rendering, and overall system
behaviour. Notably, the specifications highlight the need for a modular and object-oriented
design, indicating the creation of classes to encapsulate related functionalities for improved
code organization and maintainability. The introduction of a menu system, complete with
options for new games, settings adjustment, high-score viewing, and game exit, stands out as
a pivotal addition to the gameplay experience. The specification further emphasizes the
incorporation of audio elements, detailing the requirements for sound effects and background
music to enhance the sensory aspects of the game. The proposal for progressive difficulty
levels adds a layer of sophistication to the gameplay, contributing to a more engaging and
challenging user experience.

Non-Functional Requirements:

In addition to functional requirements, the specification addresses non-functional


aspects critical to the success of the system. The documentation emphasizes the importance
of code readability and understanding, suggesting the inclusion of inline comments and
comprehensive documentation. This ensures that learners, especially those new to C++ or
game development, can easily comprehend the intricacies of the codebase. The specification
also introduces a tutorial mode, highlighting the commitment to educational objectives. This
mode is designed to guide users through the codebase, offering explanations of key concepts,
algorithms, and design decisions, thus fostering a deeper understanding of game development
principles. These non-functional aspects are crucial for the long-term sustainability and
educational value of the project.

The system specification serves as a thorough guide for the development and
enhancement of the Snake game implementation. By addressing both functional and non-

Page 13
functional requirements, it establishes a robust foundation for the proposed system's
evolution. This detailed roadmap ensures that the resulting system will not only provide an
enriched gameplay experience but also serve as an effective educational tool, supporting
learners in their exploration of C++ and game development concepts.

3.1 HARDWARE SPECIFICATION

The hardware specifications for this Snake game implementation involve


considerations for both the development environment and the target systems where the game
will be executed.

Development Environment:

The code is designed to be developed and executed on a system that supports the SDL
(Simple DirectMedia Layer) library and TTF (TrueType Font) rendering. As SDL facilitates
multimedia functionalities, including graphics and input handling, the development machine
should have sufficient processing power and graphics capabilities. A standard development
environment would typically consist of a computer with a modern processor, a dedicated
graphics card for smooth rendering, and ample RAM to handle the compilation and execution
processes efficiently. The specifications don't impose stringent hardware requirements for
development, making it accessible to a broad range of developers.

Target System:

Considering the relatively lightweight nature of the Snake game, the target system
requirements are modest. The SDL library allows for cross-platform development, enabling
the game to run on Windows, Linux, and macOS. The game's graphics and computational
demands are minimal, making it compatible with entry-level hardware configurations. A
standard PC or laptop with a reasonably recent processor, integrated graphics, and a moderate
amount of RAM should be sufficient to run the game smoothly. The game's compatibility
with a diverse range of systems aligns with its educational focus, ensuring accessibility for
learners across various computing environments.

The hardware specifications for both the development environment and the target
systems are pragmatic, allowing for a broad audience to engage with the Snake game
implementation. The emphasis on compatibility and accessibility reflects the educational
nature of the project, encouraging learners to explore game development concepts without the

Page 14
need for high-end hardware. As a result, the Snake game remains approachable and inclusive,
facilitating a positive learning experience across diverse computing environments.

.3.2 SOFTWARE SPECIFICATION

The software specification for this Snake game implementation provides a


comprehensive overview of the system's requirements, functionalities, and design
considerations, encompassing both the SDL (Simple DirectMedia Layer) library and the core
game logic implemented in C++.

Functional Requirements:

The specification outlines the fundamental functional requirements essential for the
game's operation. This includes SDL initialization for graphics rendering and TTF
initialization for text rendering. The system's primary functionalities, such as handling user
input for snake movement, generating food, and updating the game state, are detailed with
precision. The introduction of a modular and object-oriented design is a key functional
requirement, emphasizing the encapsulation of related functionalities within classes. The
menu system, featuring options for new games, settings adjustment, high-score viewing, and
game exit, is thoroughly specified, ensuring a seamless and user-friendly experience.
Additionally, the incorporation of audio elements, including sound effects and background
music, adds an immersive dimension to the gameplay. The proposal for progressive difficulty
levels further enhances the game's functionality, introducing adaptive algorithms to
dynamically adjust the game's challenge.

Non-Functional Requirements:

In parallel with functional aspects, the specification addresses non-functional


requirements crucial for the system's success. Code readability and understanding are
prioritized, with recommendations for inline comments and comprehensive documentation.
This ensures that learners, particularly those new to C++ or game development, can navigate
and comprehend the codebase effectively. The inclusion of a tutorial mode, which guides
users through the codebase, exemplifies the commitment to educational objectives. This non-
functional aspect is essential for providing learners with insights into key concepts,
algorithms, and design decisions. The compatibility with multiple operating systems,

Page 15
facilitated by SDL's cross-platform capabilities, is emphasized, ensuring the game's
accessibility across diverse computing environments.

Educational Enhancements:

The software specification places a significant emphasis on educational aspects,


aligning with the system's purpose as a learning tool. The modular and object-oriented design
approach is not only a functional requirement but also serves pedagogical goals by
introducing learners to best practices in software architecture. The tutorial mode, designed to
explain key concepts and guide users through the codebase, contributes to a more profound
understanding of game development principles. The proposal for adaptive difficulty levels
presents an educational opportunity to explore algorithms for dynamic game progression,
reinforcing learners' comprehension of game design.

The software specification provides a robust foundation for the development and
enhancement of the Snake game implementation. By addressing functional and non-
functional requirements, along with educational enhancements, the specification ensures that
the resulting system is not only feature-rich but also serves as an effective and engaging
educational resource. This detailed roadmap guides developers and learners alike in achieving
a successful and impactful outcome.

3.3 DEVELOPING TOOLS

The development tools employed for creating this Snake game implementation reflect
a blend of industry-standard practices and accessibility, ensuring that the project remains
approachable for learners while maintaining a robust foundation for game development.

Integrated Development Environment (IDE):

The primary development tool for this project is likely to be a C++ integrated
development environment (IDE). Widely used IDEs such as Visual Studio, Code::Blocks, or
CLion provide essential features like code highlighting, debugging, and project management.
Visual Studio, in particular, offers a comprehensive suite of tools and excellent support for
C++ development, making it a popular choice. These IDEs simplify the coding process,
enhance code navigation, and provide a conducive environment for managing project
dependencies.

Page 16
Simple DirectMedia Layer (SDL):

SDL is a pivotal tool for handling multimedia components such as graphics, sound,
and input. It abstracts low-level operations, making it easier to implement features like
window creation, rendering, and event handling. SDL's cross-platform nature ensures
compatibility across different operating systems, aligning with the goal of creating an
accessible and versatile learning tool. The development team is likely to leverage SDL's
functionalities for rendering the game graphics, capturing user input, and integrating audio
elements seamlessly.

TrueType Font (TTF) Library:

For incorporating text rendering capabilities, the project relies on the TTF library, an
extension of SDL. TTF allows developers to work with TrueType fonts, enabling the display
of text elements in the game. The choice of TTF aligns with SDL, ensuring a coherent
development environment. The TTF library is crucial for rendering the score, "Game Over"
message, and potentially other textual elements within the game. Its integration contributes to
the overall aesthetics and user interface of the Snake game.

Version Control Systems:

While not explicitly mentioned in the code, version control systems like Git could be
instrumental during the development process. These systems enable collaborative work,
tracking changes, and providing a safety net through version history. Platforms like GitHub
or GitLab can host the code repository, fostering collaboration among learners and providing
a structured approach to managing code changes.

Educational Tools:

To cater to the educational aspect of the project, the inclusion of tools supporting
documentation is essential. Online platforms like Doxygen can automatically generate
documentation from source code comments, aiding learners in understanding the codebase.
Additionally, educational tools for code review and collaborative development, such as
Visual Studio Live Share, could enhance the learning experience by facilitating real-time
collaboration and knowledge sharing among learners.

Page 17
In conclusion, the development tools chosen for this Snake game implementation
strike a balance between industry-standard practices and accessibility for learners.
Leveraging familiar IDEs, SDL, TTF, and potentially version control systems contributes to a
holistic and practical learning experience, providing a solid foundation for individuals
exploring C++ game development.

Page 18
4. SYSTEM DESIGN

The system design for the Snake game implementation involves a thoughtful
approach to ensure modularity, extensibility, and an effective learning experience for
developers. The design encompasses various components, including game mechanics,
graphical rendering, user input, and educational features.

Modular and Object-Oriented Design:

The system design prioritizes a modular and object-oriented approach, encapsulating


related functionalities within classes to enhance code organization and maintainability. This
design choice enables the separation of concerns, making it easier to manage different aspects
of the game independently. Classes such as SnakeSegment, Game, and potentially others
contribute to a clear and structured architecture. The use of a linked list for representing the
snake's body further exemplifies the modularity, allowing for dynamic growth and
simplifying the addition or removal of segments.

Game Mechanics:

The design of the game mechanics focuses on providing a classic Snake gaming
experience. The MoveSnake function effectively handles the snake's movement, growth upon
consuming food, and tail segment removal when not consuming food. The introduction of
progressive difficulty levels adds a layer of complexity to the game, requiring adjustments in
the update mechanism. The careful consideration of these mechanics ensures a balance
between challenge and accessibility, aligning with the educational goals of the project.

Graphical Rendering with SDL:

SDL is leveraged for graphical rendering, and the design ensures that the rendering
functions (DrawSnake, DrawFood, DrawScore, DrawGameOver) seamlessly integrate with
the game logic. The separation of concerns between rendering and game state management
allows for flexibility in updating visuals without affecting core game mechanics. The
incorporation of TTF for displaying the score and the "Game Over" message enhances the
graphical elements, contributing to a polished user interface.

Page 19
User Input Handling:

The design for user input handling is intuitive and responsive, with SDL facilitating
the capturing of keyboard events. The integration of arrow key input allows users to control
the snake's direction, influencing its movement. The design ensures that input processing is
synchronized with the game loop, providing a smooth and interactive experience. This user-
friendly design aligns with the educational aspect of the project, catering to users with
varying levels of programming experience.

Educational Features:

The system design places a strong emphasis on educational features, promoting a


deep understanding of C++ and game development principles. The inclusion of inline
comments and comprehensive documentation supports learners in navigating and
comprehending the codebase. The tutorial mode is a notable educational feature, guiding
users through the code and explaining key concepts. This intentional design choice aims to
foster a supportive learning environment and empower users to explore and modify the code
confidently.

In conclusion, the system design for the Snake game implementation reflects a well-
considered approach that balances modularity, functionality, and educational value. The
utilization of an object-oriented structure, effective game mechanics, graphical rendering with
SDL, responsive user input handling, and educational features collectively contribute to a
system that is both accessible for learners and capable of providing a solid foundation in C++
game development.

Page 20
4.1 INPUT DESIGN

The input design for the Snake game implementation is a crucial aspect that ensures
user interaction is intuitive, responsive, and seamlessly integrated into the gaming experience.
The design leverages the SDL library to capture keyboard events, allowing users to control
the snake's movement through arrow key input.

SDL for Input Handling:

SDL provides a robust framework for handling user input events, and the design
capitalizes on this capability. The SDL event loop in the main game loop checks for user
input events, specifically SDL_KEYDOWN events, to determine when a key is pressed. The
switch-case structure efficiently processes the key code associated with arrow keys, allowing
for dynamic changes in the snake's direction based on user input. This design ensures a
responsive and real-time connection between user actions and the game's visual
representation.

Arrow Key Control:

The arrow key control design is straightforward and aligns with the expectations of
players familiar with classic Snake games. When a key is pressed, the SDL_KEYDOWN
event triggers the corresponding case in the switch statement, updating the snakeDirectionX
and snakeDirectionY variables accordingly. This design choice allows users to guide the
snake in up, down, left, or right directions seamlessly. The simplicity of the arrow key control
enhances accessibility for users of varying levels of gaming experience, making the game
approachable and engaging.

Interactive and Educational Aspect:

The input design plays a significant role in creating an interactive and educational
experience. Users actively participate in shaping the gameplay by influencing the snake's
movement. The design aligns with the educational goals of the project, providing learners
with hands-on experience in handling user input in a game development context. The
transparent mapping of arrow keys to directional changes fosters a direct correlation between
user actions and on-screen outcomes, enhancing the understanding of event-driven
programming.

Page 21
Potential Enhancements:

While the current input design effectively serves the basic needs of the Snake game,
there is room for potential enhancements. For instance, incorporating additional input
methods, such as mouse or touch controls, could diversify the gaming experience. However,
such enhancements should be approached carefully to maintain the simplicity that makes the
Snake game accessible for educational purposes.

In conclusion, the input design for the Snake game is thoughtfully crafted, utilizing
SDL's capabilities to create a responsive and user-friendly experience. The choice of arrow
key controls aligns with classic gaming conventions, contributing to the game's accessibility
and educational value. This design effectively empowers users to actively engage with the
game, making it a key component of the overall user experience.

Page 22
4.2 OUTPUT DESIGN

The output design for the Snake game implementation encompasses various aspects,
including graphical rendering using the SDL library, text rendering with the TTF library, and
the creation of a visually engaging and informative user interface.

SDL for Graphical Rendering:

The output design heavily relies on SDL for graphical rendering, leveraging its
capabilities to create a visually appealing representation of the game elements. The
SDL_RenderFillRect function is employed to draw rectangles representing the snake
segments, food, and other components on the game window. The SDL_SetRenderDrawColor
function allows for customization of colors, ensuring a clear distinction between different
entities in the game. The simplicity and efficiency of SDL contribute to a smooth rendering
process, providing users with a visually satisfying gaming experience.

TTF for Text Rendering:

Text rendering is a vital aspect of the output design, enhancing the informational
content presented to the user. The TTF library is utilized to render text elements such as the
player's score and the "Game Over" message. The TTF_RenderText_Solid function is
employed to create a text surface, and subsequently, the SDL_CreateTextureFromSurface
function converts the surface into a texture for rendering on the game window. The

Page 23
integration of TTF adds a professional and polished touch to the user interface, contributing
to the overall aesthetics of the game.

Comprehensive User Interface:

The output design focuses on creating a comprehensive user interface that not only
conveys essential information but also enhances the overall gaming experience. The
DrawSnake function effectively renders the snake segments, highlighting the snake's position
and movement. The DrawFood function visually represents the food, providing a clear target
for the player. The DrawScore function utilizes TTF to display the player's score prominently
on the screen, updating dynamically as the player progresses. The DrawGameOver function
communicates the end of the game with a visually striking "Game Over" message, signaling
to the player the conclusion of their gaming session.

Educational and Interactive Elements:

The output design plays a crucial role in the educational aspect of the project by
providing a visual representation of key game elements. The rendered graphics and text
elements serve as interactive tools, allowing learners to observe the impact of their actions in
real-time. The visual feedback from the output design reinforces the connection between code
logic and on-screen outcomes, facilitating a deeper understanding of game development
principles.

Potential Enhancements:

While the current output design effectively conveys essential information, there is
potential for further enhancements. Incorporating animations for snake movement or
additional visual effects could elevate the gaming experience. Additionally, providing
customization options for visual themes or graphics could allow users to personalize their
gaming environment.

In conclusion, the output design for the Snake game implementation is meticulously
crafted to provide a visually engaging and informative user interface. Leveraging SDL and
TTF, the design strikes a balance between simplicity and sophistication, contributing to the
overall accessibility and educational value of the project. This design not only serves the
functional requirements of the game but also enhances the user's interaction and
comprehension of game dynamics.

Page 24
Page 25
5. SYSTEM TESTING

System testing for the Snake game implementation involves a comprehensive


evaluation of its functionalities, ensuring that the game operates as intended, handles user
input accurately, and provides an engaging and error-free gaming experience. The testing
process encompasses various aspects, including game mechanics, graphical rendering, user
interface elements, and educational features.

Functionality Testing:

The core functionality of the Snake game is rigorously tested to verify that all game
mechanics operate correctly. This includes testing the snake's movement in response to user
input, proper growth upon consuming food, and the removal of tail segments when the snake
moves without consuming food. Progressive difficulty levels are assessed to ensure a
seamless transition and increased challenge as the player advances. The system is also tested
for accurate collision detection, verifying that the game correctly identifies collisions with the
game borders and the snake's own body.

Graphical Rendering and User Interface Testing:

The graphical rendering is scrutinized to confirm that game elements are displayed
correctly on the screen. This involves testing the DrawSnake and DrawFood functions to
ensure the proper representation of the snake and food entities. The DrawScore function is
assessed for dynamic updates to the player's score, providing real-time feedback. The
DrawGameOver function is tested to display the "Game Over" message appropriately when
the game concludes. The colors, fonts, and overall aesthetics are evaluated to ensure a
visually pleasing and cohesive user interface.

User Input Testing:

User input testing is crucial to guarantee that the arrow key controls respond
accurately to player actions. The system is tested to confirm that the snake changes direction
promptly and smoothly in response to user input. This testing verifies that the game maintains
interactivity and responsiveness, contributing to a positive user experience. The arrow key
controls are explored under various scenarios to ensure consistent and reliable behavior.

Page 26
Educational Feature Testing:

The educational features, such as inline comments, comprehensive documentation,


and the tutorial mode, undergo thorough testing. The inline comments and documentation are
inspected to ensure they provide sufficient guidance and explanation for learners. The tutorial
mode is tested to confirm that it effectively guides users through the codebase, explaining key
concepts and design decisions. This educational testing aims to validate that the project
serves its pedagogical goals by facilitating understanding and exploration for learners.

Potential Enhancements and Usability Testing:

The system is also assessed for potential enhancements, considering aspects like
additional features, user customization options, or improvements to the educational
components. Usability testing is conducted to evaluate the overall user experience,
identifying areas for improvement in terms of clarity, intuitiveness, and accessibility.
Feedback from usability testing may inform future iterations of the game, ensuring
continuous enhancement and refinement.

In conclusion, system testing for the Snake game is a comprehensive process that
scrutinizes functionality, graphical rendering, user input responsiveness, and educational
features. Rigorous testing ensures that the game not only operates reliably but also fulfills its
educational objectives. By addressing potential enhancements and conducting usability
testing, the system testing phase contributes to the overall quality and user satisfaction of the
Snake game implementation.

5.1 TESTING OBJECTIVES

The testing objectives for the Snake game implementation are multifaceted, aiming to
ensure the reliability, functionality, user interaction, and educational value of the project.

Functional Accuracy and Reliability:

The primary testing objective is to verify the functional accuracy of the game. This
involves rigorous testing of core functionalities such as snake movement, collision detection,
food generation, and the progressive difficulty levels. The objective is to confirm that the
game operates as intended, responding accurately to user input, and maintaining reliability
across various scenarios. This testing phase includes boundary testing to assess the robustness
of the game under extreme conditions, such as snake collisions with the game borders.

Page 27
User Interaction and Experience:

Another critical objective is to evaluate the user interaction and experience. This
involves testing the responsiveness of arrow key controls, ensuring that the snake moves
smoothly and promptly in response to user input. Usability testing assesses the overall user
experience, focusing on the clarity of game elements, the intuitiveness of controls, and the
visual appeal of the user interface. The objective is to create an engaging and user-friendly
environment, especially considering the educational context of the project.

Educational Value and Documentation:

Given the project's educational goals, testing includes an assessment of its educational
value. The inline comments and comprehensive documentation are scrutinized to ensure they
effectively guide learners through the codebase, explaining key concepts, algorithms, and
design decisions. The tutorial mode is tested to confirm its functionality in providing step-by-
step explanations, enriching the understanding of C++ and game development principles. The
objective is to create a learning environment that empowers users to comprehend and modify
the code confidently.

Adaptability and Potential Enhancements:

The testing objectives also extend to the adaptability of the codebase. This involves
assessing how well the system accommodates potential enhancements, such as new features,
customization options, or improvements to the educational components. The objective is to
ensure that the codebase is flexible and scalable, allowing for future iterations and
enhancements without compromising existing functionalities. This adaptability testing
supports the long-term sustainability and versatility of the Snake game implementation.

In conclusion, the testing objectives for the Snake game implementation encompass
functional accuracy, user interaction, educational value, and adaptability. By addressing these
objectives, the testing phase contributes to the overall quality, reliability, and educational
impact of the project. The combination of functional testing, usability testing, and educational
value assessment ensures a holistic approach to validating the Snake game implementation.

Page 28
5.2 TYPES OF TESTING

The testing process for the Snake game implementation involves various types of
testing to ensure the reliability, functionality, and educational effectiveness of the project.

Unit Testing:

Unit testing focuses on validating individual units or components of the code in


isolation. In the context of the Snake game, unit tests would target specific functions or
methods responsible for critical functionalities, such as snake movement, collision detection,
and scoring mechanisms. This type of testing ensures that each unit of code performs as
expected, facilitating early detection and resolution of potential issues.

Integration Testing:

Integration testing evaluates the interactions between different components to ensure


they work cohesively. For the Snake game, integration testing would examine how modules,
such as user input processing, graphical rendering, and game logic, seamlessly integrate. This
type of testing is crucial for identifying any discrepancies that may arise when combining
various elements, contributing to the overall stability and functionality of the game.

System Testing:

System testing assesses the complete system to validate that it meets specified
requirements. For the Snake game, system testing involves testing the entire application,
including game mechanics, graphical rendering, user interface, and educational features. This
comprehensive testing ensures that the game operates as a unified whole, meeting functional
and non-functional requirements. System testing also includes usability testing to evaluate the
overall user experience.

Functional Testing:

Functional testing aims to verify that the functionalities of the Snake game align with
the specified requirements. This involves testing scenarios such as snake movement, food
generation, scoring, and the responsiveness of user input. Functional testing ensures that the
game performs its intended operations accurately, enhancing the overall reliability and user
satisfaction.

Page 29
Usability Testing:

Usability testing assesses the user-friendliness and overall user experience of the
Snake game. Testers evaluate the clarity of the user interface, the responsiveness of controls,
and the visual appeal of the game. Usability testing is crucial, especially in an educational
context, to ensure that the game is accessible and engaging for users with varying levels of
programming experience.

Educational Testing:

Considering the educational goals of the project, educational testing focuses on


validating the effectiveness of features designed to facilitate learning. This includes testing
the tutorial mode to ensure it provides clear explanations and guidance. The inline comments
and documentation are also scrutinized to verify that they enhance the educational value of
the project, supporting learners in understanding the codebase and key programming
concepts.

In summary, the testing process for the Snake game involves a combination of unit
testing, integration testing, system testing, functional testing, usability testing, and
educational testing. This comprehensive approach ensures that the project meets both
functional requirements and educational objectives, creating a robust and impactful learning
experience for users.

Page 30
6. SYSTEM IMPLEMENTATION

The system implementation of the Snake game is a well-structured and educational


project that combines C++ programming with the Simple DirectMedia Layer (SDL) and
TrueType Font (TTF) libraries. The implementation begins with a thoughtful initialization
process, where SDL and TTF are initialized, and the game window and renderer are created.
The use of industry-standard development tools like Visual Studio and SDL contributes to a
smooth and accessible development environment. The integration of TTF for text rendering
enhances the graphical elements, providing a polished user interface.

The core of the implementation lies in the game mechanics, which are meticulously
designed to offer a classic Snake gaming experience. The snake's movement, growth upon
consuming food, and the dynamic removal of tail segments are handled with precision. The
incorporation of progressive difficulty levels adds depth to the gameplay, introducing
adaptive algorithms to dynamically adjust the game's challenge. The modular and object-
oriented design principles are evident in the creation of classes such as SnakeSegment and the
overall organization of the code, fostering code reusability and maintainability.

Graphical rendering using SDL is a standout feature of the implementation. The


DrawSnake and DrawFood functions effectively represent the game entities on the screen,
while the DrawScore and DrawGameOver functions utilize TTF to display essential
information. The use of SDL not only simplifies multimedia functionalities but also ensures
cross-platform compatibility, allowing the game to run seamlessly on various operating
systems.

The implementation also caters to educational goals by providing inline comments,


comprehensive documentation, and a tutorial mode. These elements serve as educational
tools, guiding learners through the codebase and explaining key concepts. The inclusion of
educational features aligns with the project's aim to be a learning resource, making it
accessible for users with varying levels of programming experience.

Page 31
In conclusion, the system implementation of the Snake game is a robust and well-
crafted project that effectively combines game development principles, graphical rendering
using SDL, and educational features. The modular design, integration of libraries, and
attention to detail in game mechanics contribute to a project that not only functions as a
classic Snake game but also serves as a valuable learning tool for aspiring game developers
and programmers.

6.1 IMPLEMENTATION

The Snake game implementation is a comprehensive and educational project that


successfully combines C++ programming with the SDL and TTF libraries to create a classic
and engaging gaming experience. The initiation process establishes a solid foundation,
initializing SDL and TTF while utilizing standard industry tools like Visual Studio. The
modular and object-oriented design principles are evident in the creation of the
SnakeSegment class and the overall structure, enhancing code maintainability and readability.

At the core of the implementation lies the meticulous design of the game mechanics.
The snake's movement, growth upon food consumption, and the dynamic removal of tail
segments are implemented with precision, creating a challenging yet accessible gameplay
experience. The introduction of progressive difficulty levels adds a layer of sophistication,
demonstrating an understanding of adaptive algorithms. These elements collectively
contribute to a well-crafted and enjoyable gaming experience.

Graphical rendering, facilitated by SDL, is a standout aspect of the implementation.


The DrawSnake and DrawFood functions effectively visualize game entities, while the
integration of TTF for text rendering enhances the user interface. SDL not only simplifies
multimedia tasks but also ensures cross-platform compatibility, making the game accessible
to a broader audience.

The educational focus of the implementation is evident in features like inline


comments, comprehensive documentation, and the tutorial mode. These elements guide
learners through the codebase, providing explanations for key concepts and serving as
valuable learning aids. The project's commitment to supporting users with varying levels of
programming experience aligns with its educational objectives.

Page 32
In conclusion, the Snake game implementation stands out as a well-rounded and
educational project. Its success lies in a thoughtful combination of C++ programming, SDL
and TTF libraries, and an emphasis on user guidance and educational features. The project
not only delivers a classic gaming experience but also serves as a valuable resource for those
seeking to explore game development and programming concepts in a practical and engaging
manner.

6.2 TRAINING

The training aspect of the Snake game implementation revolves around its educational
features, designed to guide users through the codebase, enhance their understanding of C++
and game development, and facilitate an immersive learning experience. The inclusion of
inline comments throughout the code serves as a form of self-guided training, providing
explanations and insights into the purpose and functionality of specific code segments. This
meticulous commenting is especially valuable for learners, as it demystifies complex code
structures and fosters comprehension.

Complementing the inline comments, the comprehensive documentation further


contributes to the training aspect of the project. It offers learners a broader perspective on the
overall architecture, design decisions, and key algorithms used in the game. This
documentation serves as a valuable resource for users seeking a more in-depth understanding
of the project's intricacies, aligning with the educational goals of the implementation.

A standout feature enhancing the training aspect is the tutorial mode, which actively
guides users through the codebase. By providing step-by-step explanations, the tutorial mode
assists learners in navigating the project, understanding key concepts, and gaining practical
insights into game development. This interactive training component ensures that users not
only play the game but also actively engage with the code, promoting a hands-on and
immersive learning experience.

In conclusion, the training aspect of the Snake game implementation is a pivotal component
of its educational focus. Through inline comments, comprehensive documentation, and an
interactive tutorial mode, the project not only facilitates user understanding of the code but
also empowers learners to explore, modify, and learn from the implementation.

Page 33
7. SYSYTEM MAINTENANCE

The system maintenance aspect of the Snake game implementation is crucial for
ensuring the long-term sustainability, adaptability, and continued educational value of the
project. Regular maintenance involves monitoring and updating the codebase to address any
issues, improve performance, and incorporate enhancements. One key element of system
maintenance is the periodic review and update of dependencies, including SDL and TTF
libraries, to leverage the latest features, security patches, and optimizations. This proactive
approach not only enhances the game's performance but also ensures compatibility with
evolving software environments.

Maintaining a modular and object-oriented codebase contributes significantly to the


ease of future updates. This design choice facilitates the identification and modification of
specific components without disrupting the entire system. The use of version control systems,
such as Git, further streamlines maintenance efforts by allowing developers to track changes,
collaborate effectively, and roll back modifications if needed. These practices collectively
contribute to a more sustainable and adaptable codebase.

Considering the educational focus of the project, system maintenance includes


updates to educational resources, such as inline comments and documentation, to reflect any
changes or improvements. As the programming landscape evolves, ensuring that learners
have access to up-to-date explanations and insights is crucial. Additionally, the tutorial mode,
being a central educational feature, may undergo enhancements to provide users with an even
more comprehensive and interactive learning experience.

Future system maintenance efforts may also explore opportunities for expanding the
game's features, introducing new gameplay mechanics, or incorporating additional
educational components. This could involve community contributions, where users and
developers collaborate to enhance the project and address emerging needs. Establishing a
feedback loop with users and the programming community contributes to ongoing
improvements and aligns with the project's commitment to fostering a supportive learning
environment.

Page 34
In conclusion, the system maintenance of the Snake game implementation is a
dynamic and on-going process that ensures the project's adaptability, performance, and
educational relevance over time. By staying vigilant to technological advancements,
maintaining a modular codebase, and regularly updating educational resources, the project
remains a valuable resource for learners and a sustainable example of C++ game
development.

Page 35
8. CONCLUSION

In conclusion, the Snake game implementation represents a successful fusion of


classic gaming, C++ programming, and educational objectives. The project not only delivers
an entertaining and well-constructed Snake game but also serves as a valuable learning
resource for individuals exploring game development and programming. The adoption of the
SDL and TTF libraries contributes to a robust graphical rendering system, enhancing the
overall gaming experience.

The system's modular and object-oriented design principles foster code


maintainability and reusability, laying the foundation for future enhancements and
adaptability. The inclusion of inline comments, comprehensive documentation, and a tutorial
mode aligns with the project's educational goals, providing users with valuable insights into
C++ programming, game development, and software design.

The emphasis on user interaction, evidenced by the responsiveness of arrow key


controls and the clarity of the user interface, contributes to an engaging gaming experience.
Furthermore, the integration of progressive difficulty levels showcases an understanding of
adaptive algorithms, catering to both novice and experienced players.

Looking forward, the project's commitment to regular system maintenance ensures its
long-term sustainability and relevance. By keeping dependencies up to date, maintaining a
modular codebase, and incorporating user feedback, the Snake game implementation remains
a dynamic and evolving resource for learners and game developers alike.

In summary, the Snake game implementation not only achieves its primary goal of
delivering a classic and enjoyable gaming experience but goes beyond by providing an
accessible and educational platform for users to delve into the intricacies of C++ game
development. The project stands as a testament to the synergy between entertainment and
education within the realm of programming and game design.

Page 36
9. FUTURE ENHANCEMENT

The Snake game implementation offers a solid foundation for potential future
enhancements, providing opportunities to expand features, improve user engagement, and
enrich the educational aspects of the project.

Additional Gameplay Features:

One avenue for future enhancement is the introduction of new gameplay features. This
could include power-ups, obstacles, or different game modes to diversify the gaming
experience. Implementing innovative mechanics would not only add complexity to the game
but also cater to users seeking a more varied and challenging gameplay.

User Customization Options:

Introducing customization options for users could enhance the overall experience. Allowing
players to choose different themes, modify the appearance of the snake, or even customize
the game environment would add a personal touch to the game. This feature could be
particularly appealing to users who want to tailor the game to their preferences.

Multiplayer Functionality:

Adding multiplayer functionality could transform the Snake game into a social experience.
Multiplayer modes, whether competitive or cooperative, could create a new dimension to the
gameplay. This feature would not only be entertaining but also foster interaction among
users, potentially leading to a community around the game.

Advanced Graphics and Animations:

Enhancements in graphical elements, such as incorporating animations for snake movement


or adding visual effects, could elevate the visual appeal of the game. While maintaining the
simplicity that makes the Snake game accessible, subtle animations and improved graphics
could contribute to a more polished and modern aesthetic.

Page 37
Expanded Educational Content:

Building on the educational focus of the project, future enhancements could include
additional educational content. This might involve expanding the tutorial mode to cover more
advanced programming concepts, providing challenges or exercises within the game, or
incorporating interactive lessons related to game development principles.

Cross-Platform Compatibility:

Ensuring compatibility with a broader range of platforms could extend the reach of the
Snake game. Adapting the implementation to run on different operating systems or platforms,
such as mobile devices, could make the game accessible to a wider audience, including users
who prefer gaming on diverse devices.

Community Collaboration:

Encouraging community collaboration could lead to ongoing enhancements and


refinements. Opening the project to contributions from the programming community allows
users to propose and implement new features, share improvements, and provide valuable
feedback. This collaborative approach fosters a sense of ownership among users and can
result in a more dynamic and evolving project.

By exploring these avenues for future enhancement, the Snake game implementation
has the potential to evolve into a more feature-rich, engaging, and versatile platform for both
gaming and learning. Each enhancement can be strategically implemented to maintain the
project's balance between accessibility and sophistication, ensuring it remains a valuable
resource for users with varying levels of experience and interest.

Page 38
10. BIBLIOGRAPHY

A typical code-based project bibliography might include references to the


programming languages, libraries, and tools used in the development. It could also mention
any specific tutorials, documentation, or textbooks that were consulted during the project. For
example:

SDL Documentation:

Reference to the official documentation for the Simple DirectMedia Layer (SDL) library
used in the project. This could include links to relevant sections of the SDL documentation
that assisted in understanding and implementing graphical rendering.

TTF Library Documentation:

Similar to SDL, if there are specific references to the TrueType Font (TTF) library, citing
the official documentation would be beneficial. This might include information on text
rendering and font handling.

C++ Programming Language Documentation:

Acknowledging the use of C++ as the programming language in the project and citing the
official C++ documentation or relevant textbooks can provide context for readers.

Programming and Game Development Textbooks:

If specific programming or game development textbooks influenced the project, those could
be cited. For example, if the project followed design patterns or principles from a particular
book, it's worth mentioning.

Page 39
APPENDIX

Source code

#include <SDL2/SDL.h>

#include <SDL2/SDL_ttf.h>

#include <iostream>

#include <cstdlib>

#include <string>

using namespace std;

const int SCREEN_WIDTH = 640;

const int SCREEN_HEIGHT = 480;

const int GRID_SIZE = 20;

bool gameOver = false;

SDL_Texture*textTexture = nullptr;

struct SnakeSegment {

int x, y;

SnakeSegment* next;

SnakeSegment(int xPos, int yPos) : x(xPos), y(yPos), next(nullptr) {}

};

Page 40
SDL_Window* window = nullptr;

SDL_Renderer* renderer = nullptr;

SnakeSegment* snakeHead = nullptr;

int foodX, foodY;

int snakeDirectionX = 1, snakeDirectionY = 0;

int score = 0;

TTF_Font* font = nullptr;

bool Init() {

if (SDL_Init(SDL_INIT_VIDEO) < 0)

cout << "SDL could not initialize! SDL_Error: " << SDL_GetError() << endl;

return false;

if (TTF_Init() == -1)

cout <<"SDL_ttf could not initialize! TTF_Error:" << TTF_GetError() << endl;

return false;

Page 41
window = SDL_CreateWindow("Snake Game", SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT,
SDL_WINDOW_SHOWN);

if (window == nullptr)

cout << "Window could not be created! SDL_Error: " << SDL_GetError() << endl;

return false;

renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

if (renderer == nullptr)

cout << "Renderer could not be created! SDL_Error: " << SDL_GetError() << endl;

return false;

font = TTF_OpenFont("C:\\Users\\user\\OneDrive\\Desktop\\TTF Font\\EduTASBeginner-


VariableFont_wght.ttf",28);

if (font==nullptr)

cout << "failed to load font!TTF_Error:" << TTF_GetError() << endl;

return false;

Page 42
}

// Create the initial snake segment at the center of the screen

int initialX = SCREEN_WIDTH / 2;

int initialY = SCREEN_HEIGHT / 2;

snakeHead = new SnakeSegment(initialX, initialY);

return true;

void GenerateFood()

foodX = rand() % (SCREEN_WIDTH / GRID_SIZE) * GRID_SIZE;

foodY = rand() % (SCREEN_HEIGHT / GRID_SIZE) * GRID_SIZE;

void DrawSnake()

SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);

SnakeSegment* segment = snakeHead;

while (segment)

SDL_Rect segmentRect = { segment->x, segment->y, GRID_SIZE, GRID_SIZE };

SDL_RenderFillRect(renderer, &segmentRect);

Page 43
segment = segment->next;

void DrawFood()

SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);

SDL_Rect foodRect = { foodX, foodY, GRID_SIZE, GRID_SIZE };

SDL_RenderFillRect(renderer, &foodRect);

void MoveSnake()

int newHeadX = snakeHead->x + snakeDirectionX * GRID_SIZE;

int newHeadY = snakeHead->y + snakeDirectionY * GRID_SIZE;

// Create a new head segment and update its next pointer

SnakeSegment* newHead = new SnakeSegment(newHeadX, newHeadY);

newHead->next = snakeHead;

snakeHead = newHead;

if (newHeadX == foodX && newHeadY == foodY) {

Page 44
GenerateFood();

score+=5;

else

// If the snake didn't eat the food, remove the tail segment

SnakeSegment* tail = snakeHead;

while (tail->next->next) {

tail = tail->next;

delete tail->next;

tail->next = nullptr;

bool CheckCollision()

int newHeadX = snakeHead->x + snakeDirectionX * GRID_SIZE;

int newHeadY = snakeHead->y + snakeDirectionY * GRID_SIZE;

if (newHeadX < 0 || newHeadX >= SCREEN_WIDTH || newHeadY < 0 || newHeadY >=


SCREEN_HEIGHT)

Page 45
return true;

// Check for collisions with the snake's own body

SnakeSegment* segment = snakeHead->next;

while (segment)

if (segment->x == newHeadX && segment->y == newHeadY)

return true;

segment = segment->next;

return false;

void DrawScore()

string scoreText = "Score: " + to_string(score);

SDL_Color textColor = {255, 255, 255}; // White color for text

SDL_Surface* textSurface = TTF_RenderText_Solid(font, scoreText.c_str(), textColor);

Page 46
if (textSurface != nullptr)

SDL_Texture* textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);

if (textTexture != nullptr)

int textWidth = textSurface->w;

int textHeight = textSurface->h;

// Calculate the position to display the score

int x = 10; // Adjust position as needed

int y = 10; // Adjust position as needed

SDL_Rect textRect = { x, y, textWidth, textHeight };

SDL_RenderCopy(renderer, textTexture, NULL, &textRect);

SDL_DestroyTexture(textTexture);

SDL_FreeSurface(textSurface);

void DrawGameOver()

Page 47
string gameOverText = "Game Over!";

SDL_Color textColor = {255, 0, 0}; // Red color for the "Game Over" message

// Render the "Game Over" text to a surface

SDL_Surface* textSurface = TTF_RenderText_Solid(font, gameOverText.c_str(),


textColor);

if (textSurface != nullptr)

// Create a texture from the text surface

textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);

if (textTexture != nullptr)

int textWidth = textSurface->w;

int textHeight = textSurface->h;

int x = SCREEN_WIDTH / 2 - textWidth / 2;

int y = SCREEN_HEIGHT / 2 - textHeight / 2;

// Define the position and dimensions of the "Game Over" message

SDL_Rect textRect = { x, y, textWidth, textHeight };

SDL_RenderCopy(renderer, textTexture, NULL, &textRect);

Page 48
}

// Free the surface

SDL_FreeSurface(textSurface);

int main(int argc, char* argv[])

if (!Init())

return 1;

GenerateFood();

bool quit = false;

SDL_Event e;

while (!quit)

while (SDL_PollEvent(&e) != 0)

Page 49
if (e.type == SDL_QUIT)

quit = true;

if (e.type == SDL_KEYDOWN)

switch (e.key.keysym.sym)

case SDLK_UP:

snakeDirectionX = 0;

snakeDirectionY = -1;

break;

case SDLK_DOWN:

snakeDirectionX = 0;

snakeDirectionY = 1;

break;

case SDLK_LEFT:

snakeDirectionX = -1;

snakeDirectionY = 0;

break;

case SDLK_RIGHT:

snakeDirectionX = 1;

snakeDirectionY = 0;

Page 50
break;

if (CheckCollision())

quit = true;

gameOver = true;

MoveSnake();

SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);

SDL_RenderClear(renderer);

DrawFood();

DrawSnake();

DrawScore();

if (gameOver)

DrawGameOver();

Page 51
SDL_RenderPresent(renderer);

SDL_Delay(100);

// Clean up the linked list

while (snakeHead)

SnakeSegment* temp = snakeHead->next;

delete snakeHead;

snakeHead = temp;

if (textTexture!= nullptr)

SDL_DestroyTexture(textTexture);

SDL_DestroyRenderer(renderer);

SDL_DestroyWindow(window);

SDL_Quit();

return 0;

Page 52
Screenshots

Page 53

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy