create snake game in tkinter in python

Here's an example code that implements the classic snake game using Python's Tkinter library:

main.py
import tkinter as tk
import random

# Define constants
CELL_SIZE = 30
GRID_WIDTH = 20
GRID_HEIGHT = 20
INITIAL_DELAY_MS = 200
MOVE_DELAY_MS = 100

# Define global variables
game_over = False
score = 0

# Initialize the snake
snake = [(1, 1), (2, 1), (3, 1)]
snake_direction = 'right'

# Initialize the food
food = (10, 10)

# Define functions
def draw_cell(pos, color):
    x, y = pos
    canvas.create_rectangle(
        x*CELL_SIZE, y*CELL_SIZE,
        x*CELL_SIZE+CELL_SIZE, y*CELL_SIZE+CELL_SIZE,
        fill=color
    )

def draw_snake():
    for cell in snake:
        draw_cell(cell, 'green')

def draw_food():
    draw_cell(food, 'red')

def move_snake():
    global game_over, score, snake_direction

    # Determine the new head position
    if snake_direction == 'up':
        new_head = (snake[0][0], snake[0][1]-1)
    elif snake_direction == 'down':
        new_head = (snake[0][0], snake[0][1]+1)
    elif snake_direction == 'left':
        new_head = (snake[0][0]-1, snake[0][1])
    elif snake_direction == 'right':
        new_head = (snake[0][0]+1, snake[0][1])

    # Check if the new head is within the game boundaries
    if new_head[0] < 0 or new_head[0] >= GRID_WIDTH \
            or new_head[1] < 0 or new_head[1] >= GRID_HEIGHT:
        game_over = True

    # Check if the new head collides with the snake's body
    if new_head in snake[1:]:
        game_over = True

    # Check if the new head collides with the food
    if new_head == food:
        snake.insert(0, new_head)
        score += 10
        new_food_position()
        canvas.itemconfig(score_text, text=f'Score: {score}')
        canvas.after(MOVE_DELAY_MS, move_snake)
        return

    # Move the snake
    snake.insert(0, new_head)
    snake.pop()
    canvas.delete('all')
    draw_snake()
    draw_food()

    # Schedule the next move
    canvas.after(MOVE_DELAY_MS, move_snake)

    # Update the score if the game is not over
    if not game_over:
        canvas.itemconfig(score_text, text=f'Score: {score}')

def new_food_position():
    global food
    new_food = None
    while new_food is None or new_food in snake:
        new_food = (random.randint(0, GRID_WIDTH-1), random.randint(0, GRID_HEIGHT-1))
    food = new_food

# Create the main window
root = tk.Tk()
root.title('Snake Game')

# Create the canvas
canvas = tk.Canvas(root, width=GRID_WIDTH*CELL_SIZE, height=GRID_HEIGHT*CELL_SIZE)
canvas.pack()

# Draw the grid lines
for i in range(GRID_WIDTH):
    canvas.create_line(i*CELL_SIZE, 0, i*CELL_SIZE, GRID_HEIGHT*CELL_SIZE)
for i in range(GRID_HEIGHT):
    canvas.create_line(0, i*CELL_SIZE, GRID_WIDTH*CELL_SIZE, i*CELL_SIZE)

# Draw the snake and the food
draw_snake()
draw_food()

# Create the score text
score_text = canvas.create_text(5, 5, anchor='nw', text=f'Score: {score}')

# Bind the arrow keys to change the snake's direction
def change_direction(event):
    global snake_direction
    if event.keysym == 'Up' and snake_direction != 'down':
        snake_direction = 'up'
    elif event.keysym == 'Down' and snake_direction != 'up':
        snake_direction = 'down'
    elif event.keysym == 'Left' and snake_direction != 'right':
        snake_direction = 'left'
    elif event.keysym == 'Right' and snake_direction != 'left':
        snake_direction = 'right'

canvas.bind_all('<Key>', change_direction)

# Start the game loop
canvas.after(INITIAL_DELAY_MS, move_snake)
root.mainloop()

3418 chars
129 lines

This code creates a Tkinter canvas where it draws the snake, the food, and the game grid. The user can control the snake's direction by pressing the arrow keys. The move_snake function is responsible for updating the snake's position, checking for collisions, and scheduling the next move. The draw_snake and draw_food functions are responsible for drawing the snake and the food on the canvas.

related categories

gistlibby LogSnag