Open naweeddashka12 opened 1 day ago
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(master, width=400, height=400, bg='black') self.canvas.pack() self.snake = [(20, 20), (20, 30), (20, 40)] self.snake_direction = 'Down' self.food_position = self.place_food() self.score = 0 self.game_running = True self.master.bind("<Key>", self.change_direction) self.update() def place_food(self): while True: x = random.randint(0, 39) * 10 y = random.randint(0, 39) * 10 if (x, y) not in self.snake: return (x, y) def change_direction(self, event): if event.keysym in ['Up', 'Down', 'Left', 'Right']: self.snake_direction = event.keysym def update(self): if self.game_running: self.move_snake() self.check_collisions() self.draw() self.master.after(100, self.update) # Update every 100 milliseconds def move_snake(self): head_x, head_y = self.snake[-1] if self.snake_direction == 'Up': new_head = (head_x, head_y - 10) elif self.snake_direction == 'Down': new_head = (head_x, head_y + 10) elif self.snake_direction == 'Left': new_head = (head_x - 10, head_y) elif self.snake_direction == 'Right': new_head = (head_x + 10, head_y) self.snake.append(new_head) # Check if food is eaten if new_head == self.food_position: self.food_position = self.place_food() self.score += 1 else: self.snake.pop(1) def check_collisions(self): head_x, head_y = self.snake[-1] # Check wall collisions if head_x < 0 or head_x >= 400 or head_y < 0 or head_y >= 400: self.game_running = False # Check self collisions if len(self.snake) != len(set(self.snake)): self.game_running = False def draw(self): self.canvas.delete(tk.ALL) # Draw the snake for segment in self.snake: self.canvas.create_rectangle(segment[0], segment[1], segment[0] + 10, segment[1] + 10, fill='green') # Draw the food food_x, food_y = self.food_position self.canvas.create_oval(food_x, food_y, food_x + 15, food_y + 15, fill='white') # Draw the score self.canvas.create_text(50, 10, text=f'Score: {self.score}', fill='white', font=('Arial',14 ))
if name == "main": root = tk.Tk() game = SnakeGame(root) root.mainloop()
It is really great code in fact we are proud of you love.
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)
if name == "main": root = tk.Tk() game = SnakeGame(root) root.mainloop()