КОД:
from tkinter import *
import random
# переменные
WIDTH = 800
HEIGHT = 600
SEG_SIZE = 20
IN_GAME = True
cl =
# вспомогательные функции
def create_block():
“”“ Создаем еду для змейки”“”
global BLOCK
posx = SEG_SIZE * random.randint(1, (WIDTH-SEG_SIZE) / SEG_SIZE)
posy = SEG_SIZE * random.randint(1, (HEIGHT-SEG_SIZE) / SEG_SIZE)
BLOCK = c.create_oval(posx, posy,
posx+SEG_SIZE, posy+SEG_SIZE,
fill=“red”)
def create_block2():
global BLOCK2
posx = SEG_SIZE * random.randint(1, (WIDTH - SEG_SIZE) / SEG_SIZE)
posy = SEG_SIZE * random.randint(1, (HEIGHT - SEG_SIZE) / SEG_SIZE)
BLOCK2 = c.create_oval(posx, posy,
posx + SEG_SIZE, posy + SEG_SIZE,
fill = “yellow”)
def create_block3():
global BLOCK3
posx = SEG_SIZE * random.randint(1, (WIDTH - SEG_SIZE) / SEG_SIZE)
posy = SEG_SIZE * random.randint(1, (HEIGHT - SEG_SIZE) / SEG_SIZE)
BLOCK3 = c.create_oval(posx, posy,
posx + SEG_SIZE, posy + SEG_SIZE,
fill = “yellow”)
class Score(object):
def __init__(self):
self.score = 0
self.x = 55
self.y = 15
c.create_text(self.x, self.y, text = “SCORE {}”.format(self.score), font=“Arial 20”, fill=“red”,tag=“score”)
def increment(self):
c.delete(“score”)
self.score += 1
c.create_text(self.x, self.y, text = “SCORE {}”.format(self.score), font=“Arial 20”, fill=“red”, tag=“score”)
def main():
“”“ Моделируем игровой процесс ”“”
global IN_GAME
if IN_GAME:
s.move()
head_coords = c.coords(s.segments.instance)
x1, y1, x2, y2 = head_coords
# проверяем на столкновения с границами игрового поля
if x2 > WIDTH or x1 < 0 or y1 < 0 or y2 > HEIGHT:
IN_GAME = False
# поедание яблока
elif head_coords == c.coords(BLOCK):
s.add_segment()
c.delete(BLOCK)
c.delete(BLOCK2)
create_block()
create_block2()
elif head_coords == c.coords(BLOCK2):
s.add_segment()
c.delete(BLOCK2)
c.delete(BLOCK)
create_block()
elif head_coords == c.coords(BLOCK3):
s.add_segment()
s.add_segment()
s.add_segment()
s.add_segment()
s.add_segment()
s.add_segment()
s.add_segment()
s.add_segment()
s.add_segment()
s.add_segment()
c.delete(BLOCK3)
# поедание себя
else:
for index in range(len(s.segments)-1):
if head_coords == c.coords(s.segments.instance):
IN_GAME = False
root.after(100, main)
# не IN_GAME -> останавливаем игру и выводим сообщение
else:
set_state(restart_text, ‘normal’)
set_state(game_over_text, ‘normal’)
class Segment(object):
“”“ Сегмент змейки ”“”
def __init__(self, x, y):
self.instance = c.create_rectangle(x, y,
x+SEG_SIZE, y+SEG_SIZE,
fill=“lime”)
class Snake(object):
“”“ Класс змейки ”“”
def __init__(self, segments):
self.segments = segments
# варианты движения
self.mapping = {“Down”: (0, 1), “Right”: (1, 0),
“Up”: (0, -1), “Left”: (-1, 0)}
# инициируем направление движения
self.vector = self.mapping
def move(self):
“”“ Движение змейки в заданном направлении”“”
for index in range(len(self.segments)-1):
segment = self.segments.instance
x1, y1, x2, y2 = c.coords(self.segments.instance)
c.coords(segment, x1, y1, x2, y2)
x1, y1, x2, y2 = c.coords(self.segments.instance)
c.coords(self.segments.instance,
x1+self.vector*SEG_SIZE, y1+self.vector*SEG_SIZE,
x2+self.vector*SEG_SIZE, y2+self.vector*SEG_SIZE)
def add_segment(self):
“”“ Добавляем сегмент змейки ”“”
score.increment()
last_seg = c.coords(self.segments.instance)
x = last_seg - SEG_SIZE
y = last_seg - SEG_SIZE
self.segments.insert(0, Segment(x, y))
def change_direction(self, event):
“”“ Выбор направления змейки ”“”
if event.keysym in self.mapping:
self.vector = self.mapping
def reset_snake(self):
for segment in self.segments:
c.delete(segment.instance)
def set_state(item, state):
c.itemconfigure(item, state=state)
def clicked(event):
global IN_GAME
s.reset_snake()
IN_GAME = True
c.delete(BLOCK)
c.delete(BLOCK2)
c.delete(BLOCK3)
c.itemconfigure(restart_text, state='hidden')
c.itemconfigure(game_over_text, state='hidden')
start_game()
def start_game():
global s
create_block()
create_block2()
create_block3()
s = create_snake()
# Reaction on keypress
c.bind(“<KeyPress>”, s.change_direction)
main()
def create_snake():
# creating segments and snake
segments = [Segment(SEG_SIZE, SEG_SIZE),
Segment(SEG_SIZE * 2, SEG_SIZE),
Segment(SEG_SIZE * 3, SEG_SIZE)]
return Snake(segments)
# настройки окна
root = Tk()
root.title(“PythonicWay Snake”)
c = Canvas(root, width=WIDTH, height=HEIGHT, bg=“#003300”)
c.grid()
# настройка нажатия клавиш
c.focus_set()
game_over_text = c.create_text(WIDTH/2, HEIGHT/2, text = “ Ты проиграл!”,
font = ‘Arial 20’, fill = ‘red’,
state = ‘hidden’)
restart_text = c.create_text(WIDTH/2, HEIGHT - HEIGHT/3,
font = ‘Arial 30’,
fill = ‘white’,
text = “Начать заново”,
state = ‘hidden’)
score = Score()
c.tag_bind(restart_text, “<Button-1>”, clicked)
start_game()
root.mainloop()