Building a Snake Game App in Python with Tkinter

The Snake game is a classic arcade game that’s not only fun to play but also a great project for learning and practicing programming. In this article, we’ll guide you through the process of creating a simple Snake game app using Python and the Tkinter library for the graphical user interface.

Prerequisites:

  1. Python: Make sure you have Python installed on your system. You can download it from the official website (https://www.python.org/downloads/).
  2. Tkinter: Tkinter is included with most Python installations, so you don’t need to install it separately.

Creating the Snake Game:

Step 1: Import Necessary Modules

Start by importing the required modules and libraries:

import tkinter as tk
import random

Step 2: Set Up the Game Window

Create the main game window and set its properties:

# Create the game window
window = tk.Tk()
window.title("Snake Game")
window.geometry("400x400")

# Create a canvas for drawing the game board
canvas = tk.Canvas(window, width=400, height=400, bg="black")
canvas.pack()

Step 3: Define Snake and Food

Define the Snake and Food classes:

class Snake:
    def __init__(self):
        self.body = [(100, 50), (90, 50), (80, 50)]
        self.direction = "Right"

class Food:
    def __init__(self):
        self.position = (random.randint(1, 19) * 20, random.randint(1, 19) * 20)

Step 4: Create the Game Functions

Define functions for starting the game, updating the game board, and handling user input:

def start_game():
    global snake, food
    snake = Snake()
    food = Food()
    canvas.delete("all")
    canvas.create_rectangle(food.position[0], food.position[1], food.position[0] + 20, food.position[1] + 20, fill="red")
    window.after(100, update_game)

def update_game():
    global snake, food

    # Move the snake
    head_x, head_y = snake.body[0]
    if snake.direction == "Up":
        new_head = (head_x, head_y - 20)
    elif snake.direction == "Down":
        new_head = (head_x, head_y + 20)
    elif snake.direction == "Left":
        new_head = (head_x - 20, head_y)
    else:
        new_head = (head_x + 20, head_y)
    snake.body = [new_head] + snake.body

    # Check for collision with food
    if snake.body[0] == food.position:
        snake.body.append((0, 0))
        food.position = (random.randint(1, 19) * 20, random.randint(1, 19) * 20)
        canvas.create_rectangle(food.position[0], food.position[1], food.position[0] + 20, food.position[1] + 20, fill="red")

    # Check for collision with walls
    if head_x < 0 or head_x >= 400 or head_y < 0 or head_y >= 400:
        canvas.create_text(200, 200, text="Game Over", font=("Arial", 20), fill="white")
    # Check for collision with itself
    elif len(snake.body) != len(set(snake.body)):
        canvas.create_text(200, 200, text="Game Over", font=("Arial", 20), fill="white")
    else:
        canvas.delete("snake")
        for segment in snake.body:
            canvas.create_rectangle(segment[0], segment[1], segment[0] + 20, segment[1] + 20, fill="green", tags="snake")
        window.after(100, update_game)

def on_key_press(event):
    global snake
    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"

window.bind("<KeyPress>", on_key_press)

Step 5: Start the Game

Start the game by creating a button to initiate it:

start_button = tk.Button(window, text="Start", command=start_game)
start_button.pack()

Step 6: Run the Game

Run the game by starting the main loop:

window.mainloop()

In this article, you have learned how to create a simple Snake game app using Python and the Tkinter library. You can expand on this foundation by adding more features like score tracking, levels, and a more visually appealing user interface. Building games is a fun way to apply your Python programming skills and gain experience in GUI development.