Fop-2 Assignment 2
Fop-2 Assignment 2
Fop-2 Assignment 2
CMS: 455443
SESSION: UG ME-2023
SUBJECT: FOP-2
Objective:
The objective of this lab was to implement a Snake game using the Python tkinter
library. The game should allow the player to control the movement of a snake on
a canvas, consume food to increase its length, and end when the snake collides
with itself or the boundaries of the canvas.
Introduction:
Snake is a classic arcade game where the player controls a snake that moves
around the screen, consuming food items to grow longer. The game ends if the
snake collides with itself or the boundaries of the game area. This lab aimed to
recreate this game using Python's tkinter library for graphical interface
development.
Implementation:
The Snake game implementation consisted of several components:
Snake Class:
The Food class represents the food items that the snake consumes to grow.
Food items appear randomly on the canvas.
Game Logic:
The next_turn function handles the main game logic.
It moves the snake, checks for collisions with food, boundaries, and itself, and
updates the game state accordingly.
User Input:
The game responds to arrow key presses to change the direction of the snake.
Key bindings are set up to capture arrow key events and update the snake's
direction accordingly.
Score Display:
The game displays the player's score, which increases each time the snake
consumes food.
Game Over:
When the game ends due to a collision, a "GAME OVER" message is displayed on
the canvas.
Results:
The implemented Snake game provides a functional and interactive experience
for the player. The snake moves smoothly across the canvas, consuming food
items to grow longer. The player's score increases with each food item consumed.
The game ends when the snake collides with itself or the boundaries of the
canvas, and a "GAME OVER" message is displayed.
Conclusion:
The Snake game implementation successfully achieved the objective of recreating
the classic arcade game using Python's tkinter library. The game provides an
enjoyable and engaging experience for players, allowing them to control the
snake's movement and compete for high scores.
CODE
import tkinter as tk
import random
class SnakeGame:
def _init_(self, master):
self.master = master
self.master.title("Snake Game")
self.master.geometry("400x430")
self.master.resizable(False, False)
self.canvas = tk.Canvas(self.master, bg="black", width=400,
height=400)
self.canvas.pack()
self.snake = [(100, 100), (90, 100), (80, 100)]
self.direction = "Right"
self.food = self.create_food()
self.score = 0
self.score_label = tk.Label(self.master, text=f"Score: {self.score}")
self.score_label.pack()
self.master.bind("<KeyPress>", self.change_direction)
self.update()
def create_food(self):
x = random.randint(0, 19) * 20
y = random.randint(0, 19) * 20
food = self.canvas.create_rectangle(x, y, x + 20, y + 20,
fill="red",tags="food")
return food
def move_snake(self):
head = self.snake[0]
if self.direction == "Right":
new_head = (head[0] + 20, head[1])
elif self.direction == "Left":
new_head = (head[0] - 20, head[1])
elif self.direction == "Up":
new_head = (head[0], head[1] - 20)
elif self.direction == "Down":
new_head = (head[0], head[1] + 20)
self.snake.insert(0, new_head)
self.snake.pop()
def check_collisions(self):
head = self.snake[0]
if head[0] < 0 or head[0] >= 400 or head[1] < 0 or head[1] >= 400:
return True
if head in self.snake[1:]:
return True
return False
def update(self):
self.move_snake()
if self.check_collisions():
print("Game Over!")
return
head = self.snake[0]
self.canvas.delete("snake")
for segment in self.snake:
self.canvas.create_rectangle(segment[0], segment[1], segment[0] +
20, segment[1] + 20, fill="green", tags="snake")
food_coords = self.canvas.coords(self.food)
if head[0] == food_coords[0] and head[1] == food_coords[1]:
self.snake.append((self.snake[-1][0]-10, self.snake[-1][1])) #
Just to increase the length
self.canvas.delete("food")
self.food = self.create_food()
self.score += 1
self.score_label.config(text=f"Score: {self.score}")
self.master.after(200, self.update)
def change_direction(self, event):
if event.keysym == "Right" and not self.direction == "Left":
self.direction = "Right"
elif event.keysym == "Left" and not self.direction == "Right":
self.direction = "Left"
elif event.keysym == "Up" and not self.direction == "Down":
self.direction = "Up"
elif event.keysym == "Down" and not self.direction == "Up":
self.direction = "Down"
if _name_ == "_main_":
root = tk.Tk()
game = SnakeGame(root)
root.mainloop()