Project
Project
Computer Project on
Snake Game
v GAME MECHANICS
vi SNAKE MOVEMENT AND GROWTH
class SnakeGame:
self.width = 600
self.height = 400
self.cell_size = 20
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 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
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")
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")
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.
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.
3.1 Initialization
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.
python
4. Game Mechanics
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.
python
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.
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
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()
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)
def show_score_window(self):
score_window = tk.Toplevel(self.master)
score_window.title("Game Over")
This window includes options to save the score or close the window.
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")
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.
Starting menu
The game
Score Board