Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
1K views21 pages

Java-Project-Snake Game

The document describes a Snake Game project created in Java. It includes an introduction that outlines the objective of navigating a snake to eat food while avoiding collisions. It then details key features such as snake movement, food generation, scoring, and collision detection. The technical implementation uses the Java Swing library. It also includes sections on requirements, system design using MVC architecture, flowchart, and core algorithm.

Uploaded by

tapstaps902
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
100% found this document useful (1 vote)
1K views21 pages

Java-Project-Snake Game

The document describes a Snake Game project created in Java. It includes an introduction that outlines the objective of navigating a snake to eat food while avoiding collisions. It then details key features such as snake movement, food generation, scoring, and collision detection. The technical implementation uses the Java Swing library. It also includes sections on requirements, system design using MVC architecture, flowchart, and core algorithm.

Uploaded by

tapstaps902
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 21

Snake Game

Micro Project Report


Title: Snake Game

1. Introduction

The Snake Game in Java is a classic arcade-style game where the player controls a snake that
moves around a grid, eating food to grow longer. The primary objective is to guide the snake to
consume as much food as possible without colliding with its own tail. The game progressively
becomes more challenging as the snake grows longer, requiring strategic planning to navigate
through the grid.

1.1 Game Overview:

The objective of the Snake Game is simple yet challenging: guide the snake to consume food,
grow longer, and achieve the highest score possible. The player controls the snake's movement
using arrow keys while avoiding collisions with the snake's own body and the grid boundaries.
As the snake grows, the game becomes progressively more demanding, requiring strategic
planning and quick reflexes.

Fig.1.1

1.2 Key Features:

 Snake Movement: Control the snake's direction using arrow keys (Up, Down, Left,
Right). Experience smooth and dynamic animation powered by Java's Swing Timer.
 Food Generation: Randomly spawned food items appear on the grid for the snake to
consume. Each consumed food item contributes to the player's score.
 Scoring System: Track and display your score as you progress through the game.
Challenge yourself to beat your highest score in subsequent plays.
 Collision Detection: The game features robust collision detection to determine
interactions between the snake, food, and grid boundaries. Colliding with the snake's
own body or the grid edges results in the end of the game.
 Game Over Screen: When the game concludes, a Game Over screen provides the
player's final score. Players have the option to restart the game for another attempt.
1
SHARAD INSTITUTE OF TECHNOLOGY, POLYTECHNIC YADRAV
Snake Game

1.3 Technical Implementation:

 Java Swing Library: Leverage the power of Java's Swing library to create an intuitive
graphical user interface.
 Timer-Based Animation: Employ a Swing Timer for precise control over snake
movement and animation.
 Event Handling: Efficiently manage user input through key event handling for
responsive gameplay.

1.4 How to Play:

 Navigate the Snake: Use the arrow keys (Up, Down, Left, Right) to control the snake's
movement.
 Consume Food: Direct the snake to consume food items to grow in length and increase
your score.
 Avoid Collisions: Prevent the snake from colliding with its own body or the grid
boundaries.
 Game Over: The game concludes when the snake collides with itself. Your final score is
displayed on the Game Over screen.

2
SHARAD INSTITUTE OF TECHNOLOGY, POLYTECHNIC YADRAV
Snake Game

2. Requirement Specification
Sr.no Name of Material Specifications Quantity Remarks

1 Desktop Computer with Windows 11, RAM 8GB 1 Yes


Required Specifications. Processor-Intel (i) Core i5

2 Software Jdk-18 1 Yes

3 Browser Chrome - Yes

4 Website 1. https://chat.openai.com/ - Yes


2. https://bard.google.com/?
utm_source=sem&utm_mediu
m=paid-
media&utm_campaign=q3enI
N_sem6

5 Reference Java Programming 1 Yes

3
SHARAD INSTITUTE OF TECHNOLOGY, POLYTECHNIC YADRAV
Snake Game

3. System Design
The Snake Game is designed as a Java Swing application that utilizes the javax.swing library
for GUI components. The game follows a simple yet effective structure, where a snake moves
within a grid, consuming food and growing longer. Below are the key components of the
system design:

1. User Interface (UI):


 The UI is created using JFrame to represent the game window.
 Graphics are drawn on the JFrame using the paint(Graphics g) method to display the
snake, food, and grid.

2. Game Logic:
 The game logic is encapsulated within the SnakeGame class, which extends JFrame.
 Snake movement, food spawning, collision detection, and game over conditions are
handled by methods within the class.

3. Timer:
 A javax.swing.Timer is used to trigger the game's actionPerformed method at regular
intervals, controlling the speed of the snake.

4. User Input:
 KeyListener interface is implemented to handle user input from arrow keys, influencing
the snake's direction.

3.1 Architecture Design

The architecture of the Snake Game involves a combination of MVC (Model-View-Controller)


and event-driven programming:
The model includes the representation of the snake, food, and their

1. Model: interactions.
Methods such as move(), spawnFood(), checkCollision(), and gameOver()
manipulate the model.

The view is responsible for rendering the graphical representation of the

2. View: model.
The paint(Graphics g) method is used to draw the snake, food, and grid on
the JFrame.

The controller manages user input and game events.


3. Controller: KeyListener and ActionListener interfaces are implemented to handle
keyboard input and timer events.

3.2 Flowchart

4
SHARAD INSTITUTE OF TECHNOLOGY, POLYTECHNIC YADRAV
Snake Game

Start Game

User Input

Move Snake

Check No
Collision

Yes Continue Game

Game Over

Display Score

End Game

1. The above flowchart represents the sequential steps in a Snake Game, starting with game
initialization, capturing user input, updating snake movement, checking for collisions, handling
game over conditions, displaying the score, and concluding with the end of the game.

2. The process outlines the game's logic, including user interaction, snake movement, collision
detection, and final score display, providing a visual overview of the game's flow from start to
finish.

4. Algorithm

5
SHARAD INSTITUTE OF TECHNOLOGY, POLYTECHNIC YADRAV
Snake Game

A step-by-step algorithm for Snake Game. This algorithm outlines the core functionality of the
program

Step 1. Initialize the Game:


 Set the title of the JFrame to "Snake Game."
 Set the size of the JFrame based on the grid size and tile size.
 Set default close operation, location, and disable resizing.
 Create an ArrayList to store snake segments.
 Add an initial segment to the snake at the center of the grid.
 Set the initial direction of the snake to 'R' (right).
 Call the spawnFood() method to generate the initial food position.
 Create a Timer that triggers the actionPerformed method every 100 milliseconds.
 Add a KeyListener to handle user input.
 Set the JFrame as focusable.

Step 2. Spawn Food:


 Generate random coordinates (x, y) for the food until the generated position is not
occupied by the snake.
 Set the food point with the generated coordinates.

Step 3. Move Snake:


 Retrieve the head of the snake.
 Calculate the new head position based on the current direction.
 If the new head position equals the food position, add a new head at that position and
call spawnFood() to generate new food.
 If not, add the new head at the calculated position and remove the last segment of the
snake.
 Check for collisions using the checkCollision() method.
 Repaint the graphics.

Step 4. Check Collision:


6
SHARAD INSTITUTE OF TECHNOLOGY, POLYTECHNIC YADRAV
Snake Game

 Retrieve the head of the snake.


 Iterate through the rest of the snake segments.
 If the head position matches any other segment, return true (collision with itself).
 If no collision is detected, return false.

Step 5. Game Over:


 Stop the timer.
 Display Option Panel with a "Game Over" message and the player's score (length of the
snake minus 1).
 Terminate the program.

Step 6. Paint Graphics:


 Override the paint method to draw the snake, food, and grid on the JFrame.
 Use different colors for the snake, food, and grid.
 Draw rectangles for each snake segment and the food.
 Draw grid lines using the drawLine method.

Step 7. Handle User Input:


 Implement the keyPressed method to capture arrow key events.
 Update the direction based on the pressed arrow key, ensuring the snake cannot reverse
its direction instantly.

Step 8. Main Method:


 Launch the SnakeGame application using SwingUtilities.invokeLater().

This algorithm outlines the main steps and logic of the Snake Game, including initializing the
game, handling user input, updating the snake's position, checking for collisions, and managing
game over conditions.

5. Explanation of Program Code

7
SHARAD INSTITUTE OF TECHNOLOGY, POLYTECHNIC YADRAV
Snake Game

1. Initialization:
 The game window is created using Java Swing.
 The grid size is set, and a snake is initialized at the center with one segment.
 The initial direction is set to the right ('R').
 The game timer is set to trigger updates every 100 milliseconds.
 KeyListener is added to capture arrow key events for controlling the snake.

2. Spawning Food:
 The spawnFood method generates random coordinates for the food, ensuring it doesn't
overlap with the snake.

3. Snake Movement:
 The move method updates the snake's position based on the current direction.
 If the snake's head reaches the food, it grows, and new food is spawned.
 If there's no food, the snake moves forward, and the last segment is removed to
maintain its length.
 Collisions are checked, and if the snake collides with itself, the game ends.

4. Checking Collisions:
 The checkCollision method compares the head of the snake with the rest of its body. If a
collision is detected, the game ends.

5. Game Over:
 The gameOver method stops the game timer, displays a message with the player's score
(length of the snake minus one), and exits the program.

6. Graphics Rendering:
 The paint method is overridden to draw the snake, food, and grid on the game window
using different colors.

7. User Input Handling:


 The keyPressed method captures arrow key events and updates the snake's direction
accordingly.

8. Main Method:
 The main method launches the SnakeGame application on the Event Dispatch Thread,
making it visible to the user.

6. Implementation

8
SHARAD INSTITUTE OF TECHNOLOGY, POLYTECHNIC YADRAV
Snake Game

6.1 Output of the program code

Step 1: Compile the Code


 Compile the Java code using the javac command: -
 This will generate a .class file.

Step 2: Run the Game


 Run the compiled Java program using the java command: -

 The Snake Game window should appear.

Step 3: Play the Game


 Use the arrow keys (Up, Down, Left, Right) to control the snake.

9
SHARAD INSTITUTE OF TECHNOLOGY, POLYTECHNIC YADRAV
Snake Game

 Try to eat the red food squares, and avoid collisions to increase your score.

Step 4: Game Over


 When the snake collides with
itself , a pop-up message will appear, showing your final score.

Step 5: Restart the Game

10
SHARAD INSTITUTE OF TECHNOLOGY, POLYTECHNIC YADRAV
Snake Game

 If you want to play again, close the game window, go back to the terminal or command
prompt, and repeat steps 1 and 2.

Step 6: Exit the Game


 Close the game window to exit the application.

7. Testing and Validation


7.1 Testing Approach
11
SHARAD INSTITUTE OF TECHNOLOGY, POLYTECHNIC YADRAV
Snake Game

The testing approach for the Hospital Snake Game focuses on ensuring the robustness,
functionality, and user experience of the game. The testing process encompasses both manual
and automated testing techniques to cover various aspects of the application.

Key Testing Objectives:


 Validate game logic, including snake movement, food generation, and collision
detection.
 Assess the responsiveness of user input and the smoothness of gameplay.
 Verify the game's compatibility with different operating systems and Java
environments.

Testing Types:
 Unit Testing: Verify the correctness of individual components, such as methods
responsible for snake movement and collision detection.
 Integration Testing: Evaluate the seamless integration of different modules, ensuring
they function cohesively.
 User Acceptance Testing (UAT): Gather feedback from potential users to assess the
game's overall usability and user experience.

Tools Used:
 JUnit for unit testing Java code.
 Manual testing for user interaction and experience.

7.2 Test Cases


A set of comprehensive test cases has been designed to cover various scenarios, ensuring that
the Hospital Snake Game meets its specified requirements.

Test Case Categories:


1. Snake Movement:
 Test snake movement in all directions (up, down, left, right).
 Verify that the snake moves one tile per game tick.
 Check the snake's response to user input for changing direction.

12
SHARAD INSTITUTE OF TECHNOLOGY, POLYTECHNIC YADRAV
Snake Game

2. Food Generation:
 Test the random spawning of food on the game board.
 Validate that food does not spawn on the snake's body.
3. Collision Detection:
 Verify detection of collisions with the game boundaries.
 Test for self-collision when the snake runs into its own body.
 Validate collision detection when the snake consumes food.
4. User Input:
 Test responsiveness to arrow key inputs.
 Verify that the snake does not move in the opposite direction (180-degree turn).
5. Scoring:
 Validate that the score increments appropriately when the snake consumes food.
6. Game Over:
 Test the game over scenario when the snake collides with boundaries or itself.
 Verify that the game stops and displays the correct score.

Test Case Execution:


Each test case is executed individually, with both successful and unsuccessful scenarios
documented. Automated tests are employed for unit testing, while manual testing is conducted
for scenarios involving user interaction and overall gameplay.

7.3 Validation Results


The validation results affirm the reliability and functionality of the Snake Game. Key findings
include:

Successful Unit Tests:


Unit tests successfully validate individual components of the game logic, ensuring accuracy
and reliability.

Responsive User Interaction:


User input, particularly arrow key responsiveness, has been validated, ensuring a smooth and
engaging gameplay experience.

13
SHARAD INSTITUTE OF TECHNOLOGY, POLYTECHNIC YADRAV
Snake Game

Effective Collision Detection:


Collision detection mechanisms prove effective, accurately identifying collisions with
boundaries, the snake's body, and food items.

Stable Game Operation:


The game demonstrates stability, operating consistently across various environments and
platforms.

Positive User Feedback:


User acceptance testing reveals positive feedback, indicating a satisfactory user experience and
a successful implementation of the Snake Game concept.

14
SHARAD INSTITUTE OF TECHNOLOGY, POLYTECHNIC YADRAV
Snake Game

8. Advantages

1. Entertainment and Recreation:


 The Snake Game provides a classic and enjoyable gaming experience.
 It offers a simple yet challenging gameplay that can be entertaining for users of all ages.

2. Educational Purpose:
 For beginners learning Java programming, this project serves as a practical exercise.
 It covers graphical user interface (GUI) development, event handling, and basic game
logic.

3. Algorithmic Thinking:
 Developing the Snake Game involves implementing algorithms for snake movement,
collision detection, and food spawning.
 It encourages algorithmic thinking and problem-solving skills.

4. User Interface Design:


 The project includes designing a graphical user interface (GUI) using Java Swing.
 Users can observe and understand the basics of UI layout, graphics rendering, and event
handling.

5. Code Modularity:
 The code is organized into methods and functions, promoting modularity and code
readability.
 Each function handles a specific aspect of the game logic, making it easier to
understand and maintain.

6. Scalability:
 The game can be extended and enhanced by adding new features, levels, or improving
graphics.
 It serves as a starting point for those interested in building more complex games using
Java.

15
SHARAD INSTITUTE OF TECHNOLOGY, POLYTECHNIC YADRAV
Snake Game

9. Disadvantages

1. Limited Features:
 The Snake Game project is relatively simple and may lack advanced features found in
more sophisticated games.

2. Graphical User Interface (GUI):


 The graphical user interface is basic and may not provide an immersive gaming
experience compared to modern game interfaces.

3. Single Player:
 The game is designed for a single player. It lacks multiplayer or online gaming features.

4. Limited Graphics:
 The graphics are basic and may not appeal to users looking for visually advanced
games.

5. Repetitive Gameplay:
 The nature of the Snake Game involves repetitive gameplay mechanics, which may
become monotonous over time. Lack of variety in challenges or levels could limit long-
term engagement for some players.

6. Scalability Challenges:
 The game may face challenges in terms of scalability. As the snake grows longer, the
gameplay area becomes more constrained, potentially making it difficult for players to
navigate and avoid collisions.

16
SHARAD INSTITUTE OF TECHNOLOGY, POLYTECHNIC YADRAV
Snake Game

10. Conclusion: -
The development of the Snake Game in Java has been a journey marked by creativity, technical
acumen, and a commitment to delivering a classic yet engaging gaming experience. The project
showcases a successful amalgamation of fundamental programming concepts, graphical user
interface design, and game logic implementation.

Future Directions
To propel the Snake Game to greater heights, potential avenues for future development include:

Enhanced Visuals: The addition of more sophisticated graphics, animations, and visual effects
could elevate the game's aesthetic appeal.

Feature Expansion: Consideration of additional gameplay elements, levels, or challenges to


cater to diverse player preferences.

Multiplayer Functionality: Exploring the implementation of multiplayer features could foster a


competitive and collaborative gaming experience.

In Conclusion, The Snake Game in Java stands as a testament to the successful execution of a
timeless gaming concept. It balances simplicity with engaging gameplay, offering a nostalgic
experience while leaving room for future innovations. The collaborative efforts, attention to
detail, and adherence to best programming practices have resulted in a project that not only
achieves its initial goals but also sets the stage for potential growth and evolution in the world
of Java game development. The Snake Game stands as a commendable achievement,
showcasing the capabilities of Java in delivering enjoyable and accessible gaming experiences.

17
SHARAD INSTITUTE OF TECHNOLOGY, POLYTECHNIC YADRAV
Snake Game

11. Reference: -
1. Jdk-18 Documentation and Resources
2. https://chat.openai.com/
3. https://bard.google.com/?utm_source=sem&utm_medium=paid-
media&utm_campaign=q3enIN_sem6
4. https://www.bing.com/chat?form=NTPCHB
5. Guided by Mrs. R. M. Patil

18
SHARAD INSTITUTE OF TECHNOLOGY, POLYTECHNIC YADRAV
Snake Game

Project Diary

BY

Ms. Tasmiya Firoj Nadaf 25034


Ms. Vedika Mahesh Nagarkar 25035
Ms. Varsha Sanjay Nimbalkar 25036
Ms. Samedha Adinath Patil 25037

Students
Sr.no Date Work done Hours Guide sign
sign
1. 8-1-24 At first, we made the 15 min
group of 5 members.

2. 10-1-24 Searched Project 1 hour


Subject.

3. 12-1-24 We took suggestions 15 min


from our guide for
selecting our project

4. 15-1-24 After selection of 1 hour


project topic wise
searched the basic
information related to it

5. 18-1-24 Then the collection of 1 hour


information was done. 30 min

19
SHARAD INSTITUTE OF TECHNOLOGY, POLYTECHNIC YADRAV
Snake Game

6. 25-1-24 Later we visited to our 30 min


guide for suggesting us
some more
information on topic
and some corrections
in collected
information.
7. 28-1-24 If there were some 1 hour
corrections then it was
corrected.

8. 3-2-24 After correcting it, we 30 min


again visited our guide
to show the corrections.

9. 10-2-24 Then we started 1 hour


searching some more
information on the
topic (for gaining some
more knowledge).

10. 12-2-24 We had a visit to our 30 min


guide after searching
some information.

11. 20-2-24 Some suggestions were 30 min


guided and we tried to
make it correct as per
the guide's requirement.

12. 24-2-24 After making some 20 min


changes we again had a
visit to our guide.

20
SHARAD INSTITUTE OF TECHNOLOGY, POLYTECHNIC YADRAV
Snake Game

13. 26-2-24 Then we started 1 hour


implementing it on the 30 min
required Software

14. 2-3-24 Then by that time, we 40 min


made the project report.

15. 15-3-24 We had visited to our 1 hour


guide to present our
project.

16. -3-24 Then we finally 1 hour


submitted our project
and project report till
this date.

21
SHARAD INSTITUTE OF TECHNOLOGY, POLYTECHNIC YADRAV

You might also like