Python:
import random
from tkinter import Tk, Canvas, NW, Label, ALL
class Constant:
board_width = 790 # ширина поля
board_height = 590 # высота поля
background = '#9ACD32'
speed_snake = 100 # скорость змейки
space_size = 15 # размер ячейки
snake_length = 3
apple_color = 'red'
body_color = '#0000FF'
head_color = '#FFFF00'
class Apple:
def __init__(self):
x = random.randint(0, (Constant.board_width//Constant.space_size)
- 1)*Constant.space_size
y = random.randint(0, (Constant.board_height // Constant.space_size)
- 1) * Constant.space_size
self.coord = [x,y]
canvas.create_oval(x, y, x + Constant.space_size, y + Constant.space_size,
fill=Constant.apple_color, outline='#FF6347')
class Snake:
def __init__(self):
self.snake_length = Constant.snake_length # длина змейки
self.coord = [[0,0]]*3
self.squares = []
for x, y in self.coord:
square = canvas.create_rectangle(x, y, x+Constant.space_size,
y+Constant.space_size,
fill=Constant.body_color, outline='#A9A9A9')
self.squares.append(square)
def move(snake, apple):
#отрисовка змейки
for x,y in snake.coord:
square = canvas.create_oval(
x, y, x + Constant.space_size, y + Constant.space_size,
fill=Constant.body_color, outline='#A9A9A9')
x,y = snake.coord[0]
#изменение координат в зависимости от направления движения
if itinerary == 'down':
y+=Constant.space_size
elif itinerary == 'up':
y-=Constant.space_size
if itinerary == 'left':
x-=Constant.space_size
if itinerary == 'right':
x+=Constant.space_size
snake.coord.insert(0,[x,y]) # вставляем на первое место списка координаты головы
square = canvas.create_oval(x,y, x+Constant.space_size, y+Constant.space_size,
fill=Constant.head_color, outline='#A9A9A9') # создается голова
snake.squares.insert(0, square) # добавляем голову в первую ячейку змейки
#задаём удаление еды при соприкосновении со змейкой
if x==apple.coord[0] and y==apple.coord[1]:
global score
score+=1
label_score.config(text='Счет: {}'.format(score))
canvas.delete('apple')
apple = Apple()
else:
# удаление хвоста после добавления головы
x, y = snake.coord[-1]
square = canvas.create_oval(x,y, x+Constant.space_size,
y+Constant.space_size, fill=Constant.background,
outline=Constant.background)
del snake.coord[-1] # удаляем координаты ячейки из списка
canvas.delete(snake.squares[-1]) # удаляем отрисовку головы
del snake.squares[-1]
#если функция столкновения вернула Истину игра заканчивается
if check_crush(snake) == True:
gameover()
else:
window.after(Constant.speed_snake, move, snake, apple) # запуск отрисовки змейки с задержкой равной speed_snake
def change_itinerary(new_itinerary):
#изменение направления змейки
global itinerary
if itinerary == 'down':
if itinerary != 'up':
itinerary = new_itinerary
if itinerary == 'up':
if itinerary != 'down':
itinerary = new_itinerary
if itinerary == 'left':
if itinerary != 'right':
itinerary = new_itinerary
if itinerary == 'right':
if itinerary != 'left':
itinerary = new_itinerary
# проверка столкновений
def check_crush(snake):
x, y = snake.coord[0] #получаем кординаты головы
#проверяем выход за границы поля
if x < 0 or x >= Constant.board_width:
return True
elif y < 0 or y >= Constant.board_height:
return True
# конец игры
def gameover():
canvas.delete(ALL)
canvas.create_text(canvas.winfo_width()/2, canvas.winfo_height()/2,
font=('Calibri-Ligth', 40), text='Конец игры')
canvas.create_text(canvas.winfo_width() / 2, canvas.winfo_height() / 2,
font=('Calibri-Ligth', 40),
text='\n\nСчёт: {}'.format(score))
if __name__ == '__main__':
window = Tk()
window.title('Змейка')
score = 0
itinerary = 'down' # направление по умолчанию
label_score = Label(window, text='Счет:{}'.format(score),
font=('Calibri-Ligth', 20))
label_score.pack()
canvas = Canvas(window, height= Constant.board_height,
width=Constant.board_width, bg=Constant.background)
canvas.pack()
window.resizable(False, False)
window.geometry("800x600+150+50")
# привязка клавиш к направлению
window.bind('<Down>', lambda event: change_itinerary('down'))
window.bind('<Up>', lambda event: change_itinerary('up'))
window.bind('<Left>', lambda event: change_itinerary('left'))
window.bind('<Right>', lambda event: change_itinerary('right'))
apple = Apple()
snake = Snake()
move(snake,apple)
window.mainloop()
Последнее редактирование: