0% found this document useful (0 votes)
47 views21 pages

Snake Game Uv

report

Uploaded by

singhtaranjot725
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)
47 views21 pages

Snake Game Uv

report

Uploaded by

singhtaranjot725
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/ 21

PROJECT REPORT

ON
SNAKE GAME
Submitted in partial fulfillment of the requirement

for the diploma of

Computer Science & Engineering

SUBMITTED TO: SUBMITTED BY:


Mrs. Prabhjit Kaur Upanshu Vasisthya

Roll no: 220189511938

Trade :- C.S.E

1
Acknowledgment

I would like to express my sincere gratitude to


everyone who supported me throughout the
development of this Snake Game project. Special
thanks to my industrial training teacher who
provided valuable feedback and guidance during
the development process. Their encouragement
and insights were crucial in shaping this project. I
am also grateful for the resources and tools that
made this project possible. Lastly, a big thank you
to my family for their unwavering support and
understanding throughout the process.
Abstract

This Snake Game project replicates the classic arcade game


using modern programming techniques. The game involves
controlling a snake to collect food items, growing longer with
each successful capture while avoiding collisions with the
walls and its own body. The project focuses on implementing
game mechanics such as smooth movement, collision
detection, and score tracking using a structured approach to
coding and problem-solving. By utilizing programming
languages and tools like Python , this project showcases not
only fundamental concepts of game development but also the
ability to create an engaging user experience. The project also
serves as a foundation for future enhancements and variations
in gameplay.
TABLE OF CONTENTS

INTRODUCTION.......................................................................................................................1

GAME DESIGN........................................................................................................................... 2

TESTING...........................................................................................................................................6

ALGORITHEM .......................................................................................................................... 9

SDLC...................................................................................................................................................12

GAME CODE...............................................................................................................................14
Project Report: Snake Game in Python
1. Introduction

1.1 Overview of the Project: The snake game is one of the classical examples of a
game that comes in an arcade, where a player maneuvers a snake that changes directions
with every food it eats and grows. A snake will be considered dead if it clashes with itself or
the walls. The objective is to create a game using Python and the Pygame library with a
graphical interface, where one can control the snake with keyboard entries.

1.2 Objectives
1. Create a Snake game: Create the necessary functions to program the basic Snake game
mechanics with Python using Pygame.

2. Provide a graphical interface: Implement a windowed environment where the game is


conducted by using Pygame.

3. Implement game logic: Functionalities of movement of snake, generation of food, collision


detection, and scoring system have to be there.

4. Better understanding of Pygame: Practical experience with Pygame and programming in


Python through this project.

2. Game Design

2.1 Game Rules

a. Use the arrow keys (up, down, left, right) to control the snake.

b. The snake keeps on moving continually in the direction of the last arrow key press.

c. The game can be won by eating the food that appears randomly on the screen.

d. The snake will grow longer whenever it eats some food.

e. The game is over when the snake hits a wall or its own body.

f. For every food eaten, the player increases his score by one.
2.2 User Interface
The game is displayed in a windowed graphical interface using Pygame. The screen shows
the snake, the food, and the player's current score. A "Game Over" message appears when
the game ends, along with the player's final score.

3. Implementation

3.1 Programming Language and Libraries


The game is implemented in Python, utilizing the Pygame library for graphical rendering
and input handling. Pygame is chosen for its simplicity and suitability for 2D game
development.

3.2 Code Structure


The code is organized into several functions and a main game loop that handles the game
logic. Below is a step-by-step explanation of the code.

3.3 Python Code Explanation


Step 1: Importing Libraries
import pygame
import time
import random

Pygame: This is the main library used to create the game. It handles the game's graphics,
sound, and input.
Time: Used to manage time-related functions, though in this script, it's mainly used to quit
the game after a delay.
Random: This library is used to generate random positions for the food on the screen.

Step 2: Initialize Pygame


pygame.init()

pygame.init(): Initializes all the Pygame modules. This step is essential to use any Pygame
functionality.

Step 3: Define Colors


white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
Colors are defined using RGB values, which will be used throughout the game for the snake,
food, background, and text.

Step 4: Set Display Dimensions


dis_width = 600
dis_height = 400

The width and height of the game window are set to 600x400 pixels.

Step 5: Create the Display Window


dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game by Python')

pygame.display.set_mode(): Creates a window of the specified dimensions.


pygame.display.set_caption(): Sets the title of the window.

Step 6: Set Game Variables


clock = pygame.time.Clock()
snake_block = 10
snake_speed = 15

clock: Used to control the game's frame rate.


snake_block: The size of each segment of the snake, which is 10x10 pixels.
snake_speed: The speed at which the snake moves, controlled by the frame rate.

Step 7: Set Up Fonts


font_style = pygame.font.SysFont('bahnschrift', 25)
score_font = pygame.font.SysFont('comicsansms', 35)

pygame.font.SysFont(): Creates font objects for rendering text on the screen. font_style is
used for messages, and score_font is used for displaying the score.

Step 8: Function to Display the Score


def your_score(score):
value = score_font.render('Your Score: ' + str(score), True, yellow)
dis.blit(value, [0, 0])

your_score(score): This function renders the current score on the screen. The score is
displayed in the top left corner.

Step 9: Function to Draw the Snake


def our_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(dis, green, [x[0], x[1], snake_block, snake_block])
our_snake(snake_block, snake_list): This function draws the snake on the screen by
iterating through the list of its segments (snake_list).

Step 10: Function to Display Messages


def message(msg, color):
mesg = font_style.render(msg, True, color)
dis.blit(mesg, [dis_width / 6, dis_height / 3])

message(msg, color): This function displays a message at the center of the screen, typically
used for the 'Game Over' message.

Step 11: Main Game Loop


def gameLoop():
game_over = False
game_close = False

gameLoop(): This function contains the main game loop, which keeps the game running
until the player loses or closes the window.
game_over and game_close: Boolean flags used to manage the game state.

x1 = dis_width / 2
y1 = dis_height / 2

x1_change = 0
y1_change = 0

snake_list = []
length_of_snake = 1

The snake's initial position is set to the center of the screen.


x1_change and y1_change: Variables to track the movement of the snake.
snake_list: A list that stores the positions of all segments of the snake.
length_of_snake: The initial length of the snake is 1.
Testing the Snake game involves several strategies to ensure that the game functions as expected, is
user-friendly, and is free of bugs. Here's a structured approach to testing the Snake game:

### 1. **Unit Testing**

- **Purpose:** Test individual components of the game, such as functions and methods.

- **Focus Areas:**

- **Movement Logic:** Verify that the snake moves correctly in response to key presses.

- **Boundary Detection:** Ensure the game detects when the snake hits the walls.

- **Food Consumption:** Check that the snake grows and the score increases when the snake
eats food.

- **Self-Collision Detection:** Test if the game correctly detects when the snake collides with
itself.

- **Tools:** You can use Python's built-in `unittest` module to automate these tests.

### 2. **Integration Testing**

- **Purpose:** Test the interaction between different components.

- **Focus Areas:**

- **Game Loop:** Ensure the game loop correctly handles events, updates game state, and
renders the display.

- **Collision Handling:** Test the integration between movement, collision detection, and game-
over conditions.

- **Score Display:** Verify that the score is accurately displayed and updated during gameplay.

### 3. **Functional Testing**

- **Purpose:** Test the game's functionality from an end-user perspective.

- **Focus Areas:**

- **User Inputs:** Verify that the arrow keys correctly control the snake.

- **Game Over Condition:** Ensure that the game ends properly when the snake hits a wall or
itself.

- **Restart and Quit:** Check that the game restarts when the user chooses to play again and
quits as expected.

### 4. **Usability Testing**

6
- **Purpose:** Ensure the game is user-friendly and enjoyable.

- **Focus Areas:**

- **User Experience:** Get feedback from users about the controls, difficulty, and overall
experience.

- **Game Instructions:** Verify that the game provides clear instructions or feedback to the
player.

### 5. **Performance Testing**

- **Purpose:** Ensure the game performs well under different conditions.

- **Focus Areas:**

- **Frame Rate:** Test the game's performance on different hardware to ensure smooth
gameplay.

- **Resource Usage:** Monitor CPU and memory usage during gameplay to identify potential
performance bottlenecks.

### 6. **Regression Testing**

- **Purpose:** Ensure that new changes or bug fixes do not introduce new issues.

- **Approach:** After making changes or updates, re-run all the previous tests to ensure
everything still works as expected.

### 7. **Acceptance Testing**

- **Purpose:** Validate the game against the initial requirements and user expectations.

- **Focus Areas:**

- **Gameplay:** Ensure the game meets all specified requirements, including functionality,
performance, and user experience.

- **User Feedback:** Gather feedback from potential users or stakeholders to ensure the game
meets their needs.

### Tools and Methods:

- **Manual Testing:** Play the game yourself or have others play it to catch any issues not covered
by automated tests.

- **Automated Testing:** Use tools like `unittest`, `pytest`, or Pygame's event handling to automate
repetitive tests.

7
Here’s an algorithm for the game logic of the Snake game. This algorithm outlines the basic steps the
game follows from initialization to game-over conditions and restarting the game.

### Algorithm for Snake Game Logic

1. **Initialize Game:**

- Import necessary libraries: `pygame`, `time`, `random`.

- Initialize the Pygame module with `pygame.init()`.

- Set up display dimensions and create the game window.

- Define colors using RGB values for the snake, food, background, and text.

- Set the snake's initial position at the center of the screen.

- Initialize variables for snake movement (`x1_change`, `y1_change`), snake size (`snake_block`),
and speed (`snake_speed`).

- Create an empty list `snake_list` to store the positions of the snake segments.

- Initialize `length_of_snake` to 1.

- Generate initial random positions for food (`foodx`, `foody`).

2. **Start Main Game Loop:**

- Set the game status flags: `game_over = False`, `game_close = False`.

3. **Check for Game Close:**

- While `game_close == True`:

- Display "You Lost!" message and current score.

- Update the display.

- Wait for player input:

- If the player presses 'Q', set `game_over = True` and `game_close = False`.

- If the player presses 'C', restart the game by calling the game loop function.

4. **Handle User Input:**

- Loop through all events using `pygame.event.get()`.

- If the `QUIT` event is detected, set `game_over = True`.

- If a `KEYDOWN` event is detected:

8
- Update `x1_change` and `y1_change` based on the arrow key pressed:

- Left arrow: `x1_change = -snake_block`, `y1_change = 0`.

- Right arrow: `x1_change = snake_block`, `y1_change = 0`.

- Up arrow: `y1_change = -snake_block`, `x1_change = 0`.

- Down arrow: `y1_change = snake_block`, `x1_change = 0`.

5. **Update Snake Position:**

- Update the snake's `x1` and `y1` position based on `x1_change` and `y1_change`.

6. **Check for Collisions:**

- **Wall Collision:**

- If the snake's `x1` or `y1` is outside the display boundaries, set `game_close = True`.

- **Self-Collision:**

- Loop through the `snake_list` (excluding the head). If the snake's head position matches any
segment in `snake_list`, set `game_close = True`.

7. **Update Snake and Food:**

- Append the new position of the snake's head to `snake_list`.

- If the length of `snake_list` exceeds `length_of_snake`, remove the oldest segment.

- Draw the background, food, and snake on the screen.

8. **Check for Food Consumption:**

- If the snake's head reaches the position of the food (`x1 == foodx` and `y1 == foody`):

- Generate new random positions for food (`foodx`, `foody`).

- Increase the snake's length by incrementing `length_of_snake`.

9. **Update the Display:**

- Display the snake and the current score.

- Update the game display with `pygame.display.update()`.

10. **Control Game Speed:**

9
- Use `clock.tick(snake_speed)` to control the frame rate and thus the speed of the snake.

11. **End the Game:**

- If `game_over` is `True`, exit the main loop and quit the game with `pygame.quit()` and `quit()`.

12. **Restart or Quit:**

- If the game ends and the player chooses to play again, restart the game by calling the game loop
function.

- If the player chooses to quit, terminate the game.

10
To create a Software Development Life Cycle (SDLC) diagram for the Snake game, I will outline the
stages and then provide you with a visual representation.

Stages of the SDLC for the Snake Game:

1. Planning:

o Define the project scope, objectives, and requirements.

o Determine the tools and technologies needed (Python, Pygame).

2. Requirements Analysis:

o Identify the game's functional and non-functional requirements.

o Gather user expectations and gameplay features (e.g., snake movement, scoring,
game over conditions).

3. Design:

o Design the game architecture and user interface.

o Create flowcharts and diagrams to represent game logic, including snake movement,
food generation, and collision detection.

4. Implementation (Coding):

o Write the code for the game using Python and Pygame.

o Implement game logic, including movement, collision detection, and score tracking.

5. Testing:

o Test the game for bugs, errors, and gameplay issues.

o Conduct unit testing, integration testing, and user acceptance testing.

6. Deployment:

o Deploy the game for use, either locally or on a platform for users to download.

o Ensure that the game runs smoothly on different systems.

7. Maintenance:

o Provide updates and bug fixes as needed.

o Gather user feedback and improve the game over time.

11
GAME CODE

import time
import random
import pygame
# Initialize Pygame pygame.init()

# Define colors
white = (255, 200, 255)
yellow = (255, 205, 202)
black = (0, 0, 0)
red = (213, 50, 80)
green = (100, 255, 0)
blue = (150, 153, 213)

# Set display dimensions


dis_width = 600
dis_height = 400

# Create the display window


dis = pygame.display.set_mode((dis_width, dis_height))

12
pygame.display.set_caption('Snake Game by Karanveer')

# Set game variables


clock = pygame.time.Clock()
snake_block = 10
snake_speed = 10

# Set up fonts for score and messages


font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)

# Function to display the score


def your_score(score):
value = score_font.render("Your Score: " + str(score),
True, yellow)
dis.blit(value, [0, 0])

# Function to draw the snake


def our_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(dis, green, [x[0], x[1], snake_block,
snake_block])

# Function to display a message on the screen


def message(msg, color):
13
mesg = font_style.render(msg, True, color)
dis.blit(mesg, [dis_width / 6, dis_height / 3])

# The main function for the game loop


def gameLoop():
game_over = False
game_close = False

x1 = dis_width / 2
y1 = dis_height / 2

x1_change = 0
y1_change = 0

snake_list = []
length_of_snake = 1

# Generate initial food position


foodx = round(random.randrange(0, dis_width -
snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height -
snake_block) / 10.0) * 10.0

while not game_over:

14
while game_close == True:
dis.fill(black)
message("You Lost! Press C-Play Again or Q-Quit",
red)
your_score(length_of_snake - 1)
pygame.display.update()

for event in pygame.event.get():


if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
gameLoop()

for event in pygame.event.get():


if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
15
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0

# Check for collision with boundaries


if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 <
0:
game_close = True
x1 += x1_change
y1 += y1_change
dis.fill(black)
pygame.draw.rect(dis, blue, [foodx, foody, snake_block,
snake_block])
snake_head = []
snake_head.append(x1)
snake_head.append(y1)
snake_list.append(snake_head)
if len(snake_list) > length_of_snake:
del snake_list[0]

# Check for collision with itself


for x in snake_list[:-1]:
16
if x == snake_head:
game_close = True

our_snake(snake_block, snake_list)
your_score(length_of_snake - 1)

pygame.display.update()

# Check if the snake eats the food


if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, dis_width -
snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height -
snake_block) / 10.0) * 10.0
length_of_snake += 1

clock.tick(snake_speed)

pygame.quit()
quit()

# Start the game


if name == " main ":
gameLoop()

17
18

You might also like