Snake Game Python Code

488

How to Code Snake game Using Python, Tkinter with the help of ChatGPT.

Source Code Here
import tkinter as tk
import random
WIDTH = 400
HEIGHT = 400
SQUARE_SIZE = 20
class SnakeGame:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title(“Snake Game”)
        self.canvas = tk.Canvas(self.root, width=WIDTH, height=HEIGHT)
        self.canvas.pack()
        self.snake = [(100, 100)]
        self.food = self.generate_food()
        self.direction = “Right”
        self.root.bind(“<Key>”, self.change_direction)
        self.update()
    def generate_food(self):
        x = random.randint(0, (WIDTH – SQUARE_SIZE) // SQUARE_SIZE) * SQUARE_SIZE
        y = random.randint(0, (HEIGHT – SQUARE_SIZE) // SQUARE_SIZE) * SQUARE_SIZE
        return x, y
    def change_direction(self, event):
        if event.keysym in [“Up”, “Down”, “Left”, “Right”]:
            self.direction = event.keysym
    def move_snake(self):
        x, y = self.snake[0]
        if self.direction == “Up”:
            y -= SQUARE_SIZE
        elif self.direction == “Down”:
            y += SQUARE_SIZE
        elif self.direction == “Left”:
            x -= SQUARE_SIZE
        elif self.direction == “Right”:
            x += SQUARE_SIZE
        self.snake.insert(0, (x, y))
        if self.snake[0] == self.food:
            self.food = self.generate_food()
        else:
            self.snake.pop()
    def check_collision(self):
        x, y = self.snake[0]
        if x < 0 or x >= WIDTH or y < 0 or y >= HEIGHT or self.snake[0] in self.snake[1:]:
            return True
        return False
    def update(self):
        self.move_snake()
        if self.check_collision():
            self.canvas.create_text(WIDTH // 2, HEIGHT // 2, text=”Game Over”, font=(“Arial”, 20))
            return
        self.canvas.delete(“all”)
        self.canvas.create_rectangle(*self.food, self.food[0] + SQUARE_SIZE, self.food[1] + SQUARE_SIZE, fill=”red”)
        for x, y in self.snake:
            self.canvas.create_rectangle(x, y, x + SQUARE_SIZE, y + SQUARE_SIZE, fill=”green”)
        self.root.after(100, self.update)
    def run(self):
        self.root.mainloop()
if __name__ == “__main__”:
    game = SnakeGame()
    game.run()