Слышал, Pygame-интерфейс у ребят в студентах популярен, но сам юзаю только tkinter. Вот код:
Программный код:
import tkinter as tk
import random
class SnakeGame:
def __init__(self, master):
self.master = master
self.master.title("Snake Game")
self.master.resizable(False, False)
self.canvas = tk.Canvas(self.master, width=500, height=500, bg="black")
self.canvas.pack()
self.snake = [(10, 10), (10, 9), (10, 8)]
self.food = None
self.score = 0
self.direction = 'Down'
self.running = True
self.place_food()
self.update()
self.master.bind("<KeyPress>", self.on_key_press)
def place_food(self):
while 1:
x = random.randint(0, 49)
y = random.randint(0, 49)
if (x, y) not in self.snake:
self.food = (x, y)
break
def update(self):
if self.running:
self.canvas.delete(tk.ALL)
for (x, y) in self.snake:
self.canvas.create_rectangle(x*10, y*10, x*10+10, y*10+10, fill="green")
self.canvas.create_rectangle(self.food[0]*10, self.food[1]*10, self.food[0]*10+10, self.food[1]*10+10, fill="red")
head_x, head_y = self.snake[0]
if self.direction == 'Up':
head_y -= 1
elif self.direction == 'Down':
head_y += 1
elif self.direction == 'Left':
head_x -= 1
elif self.direction == 'Right':
head_x += 1
new_head = (head_x, head_y)
if new_head == self.food:
self.snake.insert(0, new_head)
self.place_food()
self.score += 1
else:
self.snake = [new_head] + self.snake[:-1]
self.master.after(100, self.update)
def on_key_press(self, e):
new_direction = e.keysym
all_directions = {'Up', 'Down', 'Left', 'Right'}
opposites = {('Up', 'Down'), ('Down', 'Up'), ('Left', 'Right'), ('Right', 'Left')}
if new_direction in all_directions and (self.direction, new_direction) not in opposites:
self.direction = new_direction
if __name__ == "__main__":
root = tk.Tk()
SnakeGame(root)
root.mainloop()