Here is a simple example of how you could implement a snake game in Python using the Tkinter library. This game will involve a snake that moves around a window and eats food to grow. If the snake touches its own body or the border of the window, the game is over.
import random
import tkinter as tk
class Snake(tk.Canvas):
def __init__(self):
super().__init__(width=600, height=620, background="black", highlightthickness=0)
self.snake_pos = [(100, 100), (80, 100), (60, 100)]
self.food_pos = self.set_new_food_position()
self.score = 0
self.direction = "Right"
self.bind_all("<Key>", self.on_key_press)
self.load_assets()
self.pack()
def load_assets(self):
self.snake_body = self.create_oval(self.snake_pos[0], fill="green")
self.food = self.create_rectangle(self.food_pos, fill="white")
def set_new_food_position(self):
while True:
x_position = random.randint(1, 29)*20
y_position = random.randint(3, 29)*20
food_position = (x_position, y_position)
if food_position not in self.snake_pos:
return food_position
def on_key_press(self, e):
new_direction = e.keysym
all_directions = ["Up", "Down", "Left", "Right"]
opposites = ({"Up", "Down"}, {"Left", "Right"})
if (new_direction in all_directions and {new_direction, self.direction} not in opposites):
self.direction = new_direction
def move_snake(self):
head_x_pos, head_y_pos = self.snake_pos[0]
if self.direction == "Left":
new_head_position = (head_x_pos - 20, head_y_pos)
elif self.direction == "Right":
new_head_position = (head_x_pos + 20, head_y_pos)
elif self.direction == "Up":
new_head_position = (head_x_pos, head_y_pos - 20)
elif self.direction == "Down":
new_head_position = (head_x_pos, head_y_pos + 20)
self.snake_pos = [new_head_position] + self.snake_pos[:-1]
for segment, position in zip(self