Artificial Intelligence 17 min read

Implementing an AI-Controlled Snake Game in Python Using Curses

This article explains how to build a Python-based snake game with both human and AI players, detailing the development environment, core features, AI path‑finding logic using BFS, and providing complete source code for a fully functional AI snake that can compete against a human‑controlled snake.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Implementing an AI-Controlled Snake Game in Python Using Curses

The tutorial demonstrates how to create an AI‑driven snake game in Python, using the curses library on Windows 10 with PyCharm and Python 3.6. It first outlines the prerequisite of building a basic snake to become familiar with the curses environment.

Two main modes are described: an Intelligent Mode where the computer controls the snake automatically, and a Human‑Computer Mode where a player controls a snake via the keyboard while the AI controls another snake.

Key implementation steps include initializing the curses screen, setting up the game window, defining the snake and food positions, handling keyboard input, and implementing the game loop that updates the board, checks for collisions, and renders the snake and food.

The AI logic relies on breadth‑first search (BFS) to compute the shortest distance from each free cell to the food, then selects safe moves based on these distances. If a direct path to the food exists, the AI follows the shortest safe route; otherwise it follows the tail or chooses the longest safe move to avoid dead ends.

Below is the core source code for the basic snake implementation:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import curses, random

def Init_Curse():
    global s
    s = curses.initscr()
    curses.curs_set(0)
    curses.noecho()
    curses.cbreak()
    s.keypad(True)

def Exit_Curse():
    curses.echo()
    curses.nocbreak()
    s.keypad(False)
    curses.endwin()

def Start_Game():
    y, x = s.getmaxyx()
    w = curses.newwin(y, x, 0, 0)
    w.keypad(1)
    w.timeout(100)
    snake_x = int(x/4)
    snake_y = int(y/2)
    snake = [[snake_y, snake_x], [snake_y, snake_x-1], [snake_y, snake_x-2]]
    food_pos = [int(y/2), int(x/2)]
    w.addch(food_pos[0], food_pos[1], '@')
    # ... (game loop omitted for brevity)

if __name__ == '__main__':
    Init_Curse()
    Start_Game()
    Exit_Curse()

The extended AI version adds functions for board resetting, BFS distance calculation, move selection (shortest safe, longest safe, follow‑tail, any possible move), and virtual snake simulation to ensure the snake does not trap itself.

# Example of BFS board refresh

def board_refresh(pfood, psnake, pboard):
    queue = [pfood]
    inqueue = [0] * FIELD_SIZE
    while queue:
        idx = queue.pop(0)
        if inqueue[idx]:
            continue
        inqueue[idx] = 1
        for i in range(4):
            if is_move_possible(idx, mov[i]):
                nxt = idx + mov[i]
                if pboard[nxt] < SNAKE:
                    if pboard[nxt] > pboard[idx] + 1:
                        pboard[nxt] = pboard[idx] + 1
                    if not inqueue[nxt]:
                        queue.append(nxt)
    return True

Additional helper functions such as choose_shortest_safe_move , choose_longest_safe_move , follow_tail , and any_possible_move are used to decide the AI's next direction based on the current board state.

The article also notes common pitfalls, such as the need to enlarge the console window to avoid _curses.error: curses function returned NULL , and the extensive use of global variables when integrating the human‑controlled snake.

In summary, by following the provided code and explanations, readers can build a functional AI snake that competes with a human player, and extend it further to support multiple AI snakes or more sophisticated path‑finding algorithms.

algorithmPythonAIGame developmentSnake Gamecurses
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.