запомни import tkinter as tk import random Параметры игры WIDTH = 600 HEIGHT = 400…
- User
запомни import tkinter as tk import random
Параметры игры
WIDTH = 600 HEIGHT = 400 SEG_SIZE = 20
Цвета
BACKGROUND_COLOR = "#000000" SNAKE_COLOR = "#00FF00" FOOD_COLOR = "#FF0000"
class Snake: def init(self, canvas): self.canvas = canvas self.segments = [] self.direction = 'Right' # Начальная позиция змейки из 3 сегментов for i in range(3): x = WIDTH / 2 - SEG_SIZE * i y = HEIGHT / 2 segment = canvas.create_rectangle(x, y, x + SEG_SIZE, y + SEG_SIZE, fill=SNAKE_COLOR, outline="") self.segments.append(segment)
def move(self): # Получаем координаты головы head_coords = self.canvas.coords(self.segments[0]) x, y = head_coords[0], head_coords[1] if self.direction == 'Left': x -= SEG_SIZE elif self.direction == 'Right': x += SEG_SIZE elif self.direction == 'Up': y -= SEG_SIZE elif self.direction == 'Down': y += SEG_SIZE # Создаём новый сегмент в направлении движения new_head = self.canvas.create_rectangle(x, y, x + SEG_SIZE, y + SEG_SIZE, fill=SNAKE_COLOR, outline="") self.segments = [new_head] + self.segments[:-1] def grow(self): # Добавляем новый сегмент в конец змейки tail = self.segments[-1] tail_coords = self.canvas.coords(tail) x, y = tail_coords[0], tail_coords[1] if self.direction == 'Left': x += SEG_SIZE elif self.direction == 'Right': x -= SEG_SIZE elif self.direction == 'Up': y += SEG_SIZE elif self.direction == 'Down': y -= SEG_SIZE new_tail = self.canvas.create_rectangle(x, y, x + SEG_SIZE, y + SEG_SIZE, fill=SNAKE_COLOR, outline="") self.segments.append(new_tail) def set_direction(self, new_direction): # Запрещаем змейке двигаться в обратную сторону opposites = {'Left': 'Right', 'Right': 'Left', 'Up': 'Down', 'Down': 'Up'} if new_direction != opposites.get(self.direction): self.direction = new_direction def head_collision(self, x, y): # Проверяем столкновение головы с телом змейки for segment in self.segments[1:]: coords = self.canvas.coords(segment) if coords[0] == x and coords[1] == y: return True return Falseclass Food: def init(self, canvas, snake): self.canvas = canvas self.snake = snake self.id = None self.position = (0, 0) self.spawn()
def spawn(self): while True: x = random.randint(0, (WIDTH - SEG_SIZE) // SEG_SIZE) * SEG_SIZE y = random.randint(0, (HEIGHT - SEG_SIZE) // SEG_SIZE) * SEG_SIZE collision = False for segment in self.snake.segments: seg_coords = self.canvas.coords(segment) if seg_coords[0] == x and seg_coords[1] == y: collision = True break if not collision: break self.position = (x, y) if self.id: self.canvas.delete(self.id) # Удаляем предыдущую еду, если она есть self.id = self.canvas.create_oval(x, y, x + SEG_SIZE, y + SEG_SIZE, fill=FOOD_COLOR, outline="") - Assistant
Конечно, я ознакомился с предоставленным кодом игры "Змейка" на Python с использованием библиотеки
tkinter. Чем я могу помочь? Возможно, вы хотите улучшить функциональность, добавить новые возможности, оптимизировать код или исправить какие-либо ошибки?Если у вас есть конкретные вопросы или задачи, связанные с этим кодом, пожалуйста, сообщите, и я с радостью помогу!