from tkinter import * import random w = 740 h = 540 a = 20 T = 100 IN_GAME = True PAUSE = False def quicker(): global T if T>40: T-=20 def slower(): global T T+=20 def create_block(): global BLOCK x = a * random.randint(1,(w-a)/a) y = a * random.randint(1,(h-a)/a) BLOCK = c.create_oval(x, y, x+a, y+a, fill="red") class Segment(object): def __init__(self, x, y): self.instance = c.create_rectangle(x,y,x+a,y+a,fill="white") 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["Right"] def move(self): # метод руху в поточному напрямку for index in range(len(self.segments)-1): segment = self.segments[index].instance x1, y1, x2, y2 = c.coords(self.segments[index+1].instance) c.coords(segment, x1, y1, x2, y2) x1, y1, x2, y2 = c.coords(self.segments[-2].instance) c.coords(self.segments[-1].instance, x1+self.vector[0]*a, y1+self.vector[1]*a, x2+self.vector[0]*a, y2+self.vector[1]*a) def add_segment(self): # додавання сегмента last = c.coords(self.segments[0].instance) x = last[0] y = last[1] self.segments.insert(0, Segment(x, y)) def change_direction(self, event): if event.keysym in self.mapping: self.vector = self.mapping[event.keysym] def new(): global b1,b2,b3,b4,c,root, IN_GAME del b1,b2,b3,b4,c IN_GAME = True root.destroy() start() def start(): global b1,b2,b3,b4,c,root, IN_GAME root = Tk() root.title("Гра «Змійка»") c = Canvas(root, width=w, height=h, bg="#005500") c.grid(row=0, column=0, columnspan=4) c.focus_set() b1 = Button (root, text='Нова гра', width=14, height=1, bg='white', fg='black', font='ubuntu 15') b2 = Button (root, text='Пришвидшити',width=14, height=1, bg='white', fg='black', font='ubuntu 15') b3 = Button (root, text='Сповільнити',width=14, height=1, bg='white', fg='black', font='ubuntu 15') b4 = Button (root, text='|| / ► ', width=14, height=1, bg='white', fg='black', font='ubuntu 15') b1.grid(row=1, column=0) b2.grid(row=1, column=1) b3.grid(row=1, column=2) b4.grid(row=1, column=3) s = Snake([Segment(a,a), Segment(a*2,a), Segment(a*3,a)]) create_block() def main(): # основну функція керування перебігом гри global IN_GAME, BLOCK if IN_GAME: s.move() head_coords = c.coords(s.segments[-1].instance) x1, y1, x2, y2 = head_coords if x2 > w or x1 < 0 or y1 < 0 or y2 > h: IN_GAME = False elif head_coords == c.coords(BLOCK): s.add_segment() c.delete(BLOCK) create_block() else: for index in range(len(s.segments)-1): if head_coords == c.coords(s.segments[index].instance): IN_GAME = False if not PAUSE: root.after(T, main) else: c.create_text(w/2, h/2, text="Гру завершено з довжиною змійки "+str(len(s.segments)), font="Ubuntu 28", fill="yellow") def set(): global PAUSE PAUSE = not PAUSE if not PAUSE: main() c.bind("", s.change_direction) b1.bind('', lambda event: new()) b2.bind('', lambda event: quicker()) b3.bind('', lambda event: slower()) b4.bind('', lambda event: set()) main() root.mainloop() start()