0% found this document useful (0 votes)
6 views

Project

This document presents a computer project on the implementation of the Snake Game using Python and the tkinter library, fulfilling academic requirements for the 2024-25 year. It includes acknowledgments, a detailed code structure, game mechanics, and functionalities such as snake movement, food placement, collision detection, and score saving. The project serves as an introduction to game development in Python, highlighting key programming concepts and providing an interactive user experience.

Uploaded by

grgzoe03
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)
6 views

Project

This document presents a computer project on the implementation of the Snake Game using Python and the tkinter library, fulfilling academic requirements for the 2024-25 year. It includes acknowledgments, a detailed code structure, game mechanics, and functionalities such as snake movement, food placement, collision detection, and score saving. The project serves as an introduction to game development in Python, highlighting key programming concepts and providing an interactive user experience.

Uploaded by

grgzoe03
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/ 17

RAI SCHOOL

Naxal, Kathmandu, Nepal

Computer Project on
Snake Game

This research/ practical is presented for partial fulfillment


of partial requirement as per the guidelines issued by
Central Board of Secondary Education, New Delhi, India for
academic year 2024-25.

Submitted By: Supervised By:

Name: Kunsang Tamang Teacher’s Name: Sanjay Gopal


Class: 12 Subject: Computer
Board Roll No: Department: Computer
Acknowledgment

I would like to express my sincere gratitude to my


teachers at RAI School for their invaluable guidance and
support throughout this project. Your insights and
encouragement have been instrumental in shaping my
understanding of the Python Programing

I also wish to thank my family and friends for their


unwavering support and motivation. Their belief in my
abilities inspired me to delvelop deeper into this
fascinating epic and its teachings.

This project has not only enhanced my knowledge of our


Computational and Programming skill and gave me a
insight on how it works.
TABLE OF CONTENTS
i CODE
ii INTRODUCTION

iii OVERVIEW OF THE CODE STRUCTURE


iv THE SNAKE GAME CLASS

v GAME MECHANICS
vi SNAKE MOVEMENT AND GROWTH

vii DRAWING THE GAME ELEMENTS

viii GAME OVER HANDLING

ix SAVING SCORES TO A FILE


x LEVEL SELECTION
xi CONCLUSION
import tkinter as tk
import random
import time
from tkinter import filedialog

class SnakeGame:

def __init__(self, master, level):


self.master = master
self.master.title("Snake Game")

self.width = 600
self.height = 400
self.cell_size = 20

self.canvas = tk.Canvas(master, width=self.width,


height=self.height, bg='black')
self.canvas.pack()

self.snake = [(100, 100), (80, 100), (60, 100)]


self.direction = 'Right'
self.food = self.place_food()
self.score = 0
self.level = level

self.master.bind("<Key>", self.change_direction)
self.game_over = False

self.run_game()

def place_food(self):
x = random.randint(0, (self.width // self.cell_size) - 1)
* self.cell_size
y = random.randint(0, (self.height // self.cell_size) - 1)
* self.cell_size
return (x, y)

def change_direction(self, event):


if event.keysym in ['Up', 'Down', 'Left', 'Right']:
self.direction = event.keysym

def run_game(self):
if not self.game_over:
self.update_snake()
self.check_collisions()
self.draw_elements()
self.master.after(100 - (self.level - 1) * 20,
self.run_game) # Increase speed with level

def update_snake(self):
head_x, head_y = self.snake[0]
if self.direction == 'Up':
head_y -= self.cell_size
elif self.direction == 'Down':
head_y += self.cell_size
elif self.direction == 'Left':

head_x -= self.cell_size
elif self.direction == 'Right':
head_x += self.cell_size

self.snake.insert(0, (head_x, head_y))

if (head_x, head_y) == self.food:


self.food = self.place_food()
self.score += 1
if self.score % 5 == 0: # Increase level every 5
points
self.level += 1
else:
self.snake.pop()

def check_collisions(self):
head_x, head_y = self.snake[0]
if (head_x < 0 or head_x >= self.width or
head_y < 0 or head_y >= self.height or
len(self.snake) != len(set(self.snake))): # Check for
self-collision
self.game_over = True
self.show_score_window()

def draw_elements(self):
self.canvas.delete(tk.ALL)
for i, (x, y) in enumerate(self.snake):
color = 'green'
if i < 7 and self.score > i: # Show letters KUNSANG
for first 7 scores
letter = "KUNSANG"[i]
self.canvas.create_rectangle(x, y, x +
self.cell_size, y + self.cell_size, fill=color)
self.canvas.create_text(x + self.cell_size // 2, y
+ self.cell_size // 2, text=letter, fill='white')
else:
self.canvas.create_rectangle(x, y, x +
self.cell_size, y + self.cell_size, fill=color)
food_x, food_y = self.food
self.canvas.create_oval(food_x, food_y, food_x +
self.cell_size, food_y + self.cell_size, fill='red')
self.canvas.create_text(50, 10, text=f'Score:
{self.score}', fill='white')

def show_score_window(self):
score_window = tk.Toplevel(self.master)
score_window.title("Game Over")

label = tk.Label(score_window, text=f"Your Score:


{self.score}", font=("Arial", 16))
label.pack(pady=20)

save_button = tk.Button(score_window, text="Save Score",


command=self.save_result)
save_button.pack(pady=5)

close_button = tk.Button(score_window, text="Close",


command=score_window.destroy)
close_button.pack(pady=5)

def save_result(self):
file_path =
filedialog.asksaveasfilename(defaultextension=".txt",
filetypes=
[("Text files", "*.txt"), ("All files", "*.*")])
if file_path:
with open(file_path, 'a') as file:
file.write(f'Score: {self.score}, Level:
{self.level}, Time: {time.ctime()}\n')

class LevelSelection:
def __init__(self, master):
self.master = master
self.master.title("Select Difficulty Level")

self.label = tk.Label(master, text="Select Difficulty


Level", font=("Arial", 16))
self.label.pack(pady=20)

self.easy_button = tk.Button(master, text="Easy",


command=lambda: self.start_game(1))
self.easy_button.pack(pady=5)

self.medium_button = tk.Button(master, text="Medium",


command=lambda: self.start_game(2))
self.medium_button.pack(pady=5)
self.hard_button = tk.Button(master, text="Hard",
command=lambda: self.start_game(3))
self.hard_button.pack(pady=5)

def start_game(self, level):


self.master.destroy() # Close the level selection window
game_window = tk.Tk()
game = SnakeGame(game_window, level)
game_window.mainloop()

if __name__ == "__main__":
root = tk.Tk()
level_selection = LevelSelection(root)
root.mainloop()
Title: Understanding the Snake Game
Implementation in Python

Introduction
The Snake game is a classic arcade game that has entertained players for
decades. In this implementation, we utilize the tkinter library in Python to
create a graphical user interface (GUI) for the game. The game
features a controllable snake that grows longer as it consumes food, and
it includes levels of difficulty, score tracking, and the ability to save scores
to a file.

1. Overview of the Code Structure


The program is organized into several classes and functions that
encapsulate different functionalities:

SnakeGame Class: Manages the game logic, including snake


movement, food placement, collision detection, and score
management.

LevelSelection Class: Provides a GUI for selecting the difficulty level


before starting the game.
Main Execution Block: Initializes the application and starts the level
selection window.

2. Importing Required Libraries


At the beginning of the code, we import necessary libraries:

import tkinter as tk
import random
import time
from tkinter import filedialog
tkinter: This is the standard GUI toolkit for Python, allowing us to
create windows, buttons, and other interface elements.

random: Used to generate random positions for food on the game


canvas.
time: Provides a way to record and display the time when the score is
saved.
filedialog: This module helps in creating file dialogs for saving files.

3. The SnakeGame Class

3.1 Initialization

The SnakeGame class initializes the game environment:

class SnakeGame:
def __init__(self, master, level):
self.master = master
self.master.title("Snake Game")

self.width = 600
self.height = 400
self.cell_size = 20

master: The main window for the game, passed from the level
selection.

width, height: Dimensions of the game canvas.

cell_size: Size of each segment of the snake and the food.

3.2 Canvas Creation

The game uses a canvas to draw the snake and food:

python

self.canvas = tk.Canvas(master, width=self.width,


height=self.height, bg='black')
self.canvas.pack()

3.3 Game Variables

Several variables are initialized to manage the game state:

self.snake = [(100, 100), (80, 100), (60, 100)] # Initial snake


segments
self.direction = 'Right' # Initial direction
self.food = self.place_food() # Initial food placement
self.score = 0 # Initial score
self.level = level # Game level
self.master.bind("<Key>", self.change_direction) # Key binding
for direction change
self.game_over = False # Game state

4. Game Mechanics

4.1 Food Placement

The place_food method generates a random position for the food:

def place_food(self):
x = random.randint(0, (self.width // self.cell_size) - 1) *
self.cell_size
y = random.randint(0, (self.height // self.cell_size) - 1) *
self.cell_size
return (x, y)

This ensures that the food appears within the bounds of the canvas.

4.2 Direction Change

The change_direction method allows the player to control the snake:

python

def change_direction(self, event):


if event.keysym in ['Up', 'Down', 'Left', 'Right']:
self.direction = event.keysym

This method updates the direction based on the key pressed.

4.3 Game Loop

The run_game method is the main loop that keeps the game running:

def run_game(self):
if not self.game_over:
self.update_snake()
self.check_collisions()
self.draw_elements()
self.master.after(100 - (self.level - 1) * 20,
self.run_game) # Adjust speed based on level

This method updates the snake's position, checks for collisions, and
redraws the game elements.

5. Snake Movement and Growth

5.1 Updating the Snake

The update_snake method handles the snake's movement and growth:

def update_snake(self):
head_x, head_y = self.snake[0]
if self.direction == 'Up':
head_y -= self.cell_size
elif self.direction == 'Down':
head_y += self.cell_size
elif self.direction == 'Left':
head_x -= self.cell_size
elif self.direction == 'Right':
head_x += self.cell_size

self.snake.insert(0, (head_x, head_y)) # Add new head


position
if (head_x, head_y) == self.food:
self.food = self.place_food() # Reposition food
self.score += 1 # Increase score
if self.score % 5 == 0: # Increase level every 5 points
self.level += 1
else:
self.snake.pop() # Remove last segment if not eating

5.2 Collision Detection

The check_collisions method determines if the snake has collided with


walls or itself:

python

def check_collisions(self):
head_x, head_y = self.snake[0]
if (head_x < 0 or head_x >= self.width or
head_y < 0 or head_y >= self.height or
len(self.snake) != len(set(self.snake))): # Self-
collision check
self.game_over = True
self.show_score_window()

If a collision is detected, the game ends, and the score window is


displayed.

6. Drawing the Game Elements


The draw_elements method is responsible for rendering the snake and
food on the canvas:

python

def draw_elements(self):
self.canvas.delete(tk.ALL) # Clear canvas
for i, (x, y) in enumerate(self.snake):
color = 'green'
if i < 7 and self.score > i: # Show letters KUNSANG for
first 7 scores
letter = "KUNSANG"[i]
self.canvas.create_rectangle(x, y, x + self.cell_size,
y + self.cell_size, fill=color)
self.canvas.create_text(x + self.cell_size // 2, y +
self.cell_size // 2, text=letter, fill='white')
else:
self.canvas.create_rectangle(x, y, x + self.cell_size,
y + self.cell_size, fill=color)

food_x, food_y = self.food


self.canvas.create_oval(food_x, food_y, food_x +
self.cell_size, food_y + self.cell_size, fill='red')
self.canvas.create_text(50, 10, text=f'Score: {self.score}',
fill='white')

This method uses the create_rectangle and create_oval methods to


draw the snake and food, respectively.

7. Game Over Handling


When the game ends, a new window is displayed showing the player's
score:

def show_score_window(self):
score_window = tk.Toplevel(self.master)
score_window.title("Game Over")

label = tk.Label(score_window, text=f"Your Score:


{self.score}", font=("Arial", 16))
label.pack(pady=20)

save_button = tk.Button(score_window, text="Save Score",


command=self.save_result)
save_button.pack(pady=5)

close_button = tk.Button(score_window, text="Close",


command=score_window.destroy)
close_button.pack(pady=5)

This window includes options to save the score or close the window.

8. Saving Scores to a File


The save_result method allows players to save their scores to a text
file:

def save_result(self):
file_path =
filedialog.asksaveasfilename(defaultextension=".txt",
filetypes=[("Text
files", "*.txt"), ("All files", "*.*")])
if file_path:
with open(file_path, 'a') as file:
file.write(f'Score: {self.score}, Level: {self.level},
Time: {time.ctime()}\n')

This method opens a file dialog where users can choose the location and
name of the file to save their score.

9. Level Selection
The LevelSelection class provides an interface to select the game
difficulty:

class LevelSelection:
def __init__(self, master):
self.master = master
self.master.title("Select Difficulty Level")

self.label = tk.Label(master, text="Select Difficulty


Level", font=("Arial", 16))
self.label.pack(pady=20)

self.easy_button = tk.Button(master, text="Easy",


command=lambda: self.start_game(1))
self.easy_button.pack(pady=5)

self.medium_button = tk.Button(master, text="Medium",


command=lambda: self.start_game(2))
self.medium_button.pack(pady=5)

self.hard_button = tk.Button(master, text="Hard",


command=lambda: self.start_game(3))
self.hard_button.pack(pady=5)

def start_game(self, level):


self.master.destroy() # Close the level selection window
game_window = tk.Tk()
game = SnakeGame(game_window, level)
game_window.mainloop()

This class creates buttons for selecting Easy, Medium, or Hard levels and
starts the game with the chosen difficulty.

10. Conclusion
This implementation of the Snake game in Python using tkinter
demonstrates how to create an interactive GUI application. The game
encapsulates various programming concepts such as object-oriented
programming, event handling, and file I/O. Players can enjoy a classic
game experience while also having the option to save their scores for
future reference.

By breaking down the code into manageable sections, we can understand


how each part contributes to the overall functionality of the game. This
project serves as an excellent introduction to game development in
Python and provides a foundation for further exploration of GUI
applications.
Project Overview

Starting menu

The game
Score Board

Saving the score

You might also like