import tkinter as tk
from enum import Enum
CELL = 20
WIDTH, HEIGHT = 400, 400
class Direction(Enum):
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
class Snake:
def __init__(self, x, y):
self.x, self.y = x, y
self.direction = Direction.UP
def move(self):
dx, dy = self.direction.value
self.x += dx
self.y += dy
def draw(self, canvas):
canvas.create_rectangle(
self.x, self.y,
self.x + CELL, self.y + CELL,
fill="#933", outline=""
)
class App:
def __init__(self, root):
self.root = root
self.root.title("Snake")
self.canvas = tk.Canvas(root, width = WIDTH, height = HEIGHT, bg="#F99")
self.canvas.pack()
self.snake = Snake(WIDTH // 2, HEIGHT // 2)
self.root.bind("<Key>", self.on_key)
self.tick()
def on_key(self, event):
mapping = {
"Up": Direction.UP,
"Down": Direction.DOWN,
"Left": Direction.LEFT,
"Right": Direction.RIGHT,
}
if event.keysym in mapping:
self.snake.direction = mapping[event.keysym]
def tick(self):
self.snake.move()
self.snake.draw(self.canvas)
self.root.after(100, self.tick)
if __name__ == "__main__":
root = tk.Tk()
App(root)
root.mainloop()