запомни код import tkinter as tk import random Параметры игры WIDTH = 600 HEIGHT = 400…
- User
запомни код import tkinter as tk import random
Параметры игры
WIDTH = 600 HEIGHT = 400 SEG_SIZE = 20 IN_GAME = True
Цвета
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) self.id = self.canvas.create_oval(x, y, x + SEG_SIZE, y + SEG_SIZE, fill=FOOD_COLOR, outline="") - Assistant
Отлично! Я ознакомился с вашим кодом игры "Змейка" на Python с использованием библиотеки Tkinter. Вот краткий обзор того, что делает каждая часть кода:
-
Импорты и настройки:
- Импортируются необходимые модули:
tkinterдля создания графического интерфейса иrandomдля генерации случайных позиций еды. - Задаются параметры игры, такие как размеры окна, размер сегмента змейки, цвета и начальное состояние игры.
- Импортируются необходимые модули:
-
Класс
Snake:- Управляет змейкой, включая её сегменты, направление движения и методы для перемещения (
move), увеличения длины (), изменения направления () и проверки столкновений головы с телом ().
- Управляет змейкой, включая её сегменты, направление движения и методы для перемещения (
-