Implementing an AI-Powered Snake Game in Python with Curses
This tutorial walks through building an AI-controlled Snake game in Python using the curses library, covering environment setup, core algorithms such as BFS/DFS for pathfinding, detailed code explanations, common pitfalls, and extensions for human‑vs‑AI play.
This article explains how to create an AI‑driven Snake game in Python using the curses library, providing both autonomous (AI) and human‑vs‑AI gameplay modes.
Key features: 1) Intelligent mode where the computer controls the snake, 2) Human‑vs‑computer mode, and 3) a foundation for extending to computer‑vs‑computer or player‑vs‑player battles.
Implementation environment: PyCharm, Python 3.6, curses, Windows 10.
Step‑by‑step process: Install curses (see the provided links), review the inspiration source, understand the algorithmic ideas (BFS + DFS for path‑finding), and first build a basic Snake using curses.
Core code (unchanged):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/11/5 17:08
# @Author : Empirefree
# @File : 贪吃蛇-01.py
# @Software: PyCharm Community Edition
# curses official docs: https://docs.python.org/3.5/library/curses.html#module-curses
# curses reference: https://blog.csdn.net/chenxiaohua/article/details/2099304
import curses
import 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], '@')
key = curses.KEY_RIGHT
while True:
next_key = w.getch()
if next_key != -1:
if (key == curses.KEY_RIGHT and next_key != curses.KEY_LEFT) or \
(key == curses.KEY_LEFT and next_key != curses.KEY_RIGHT) or \
(key == curses.KEY_DOWN and next_key != curses.KEY_UP) or \
(key == curses.KEY_UP and next_key != curses.KEY_DOWN):
key = next_key
# death check, movement, food handling omitted for brevity
# ...
if snake[0][0] in [0, y] or snake[0][1] in [0, x] or snake[0] in snake[1:]:
curses.endwin()
print('!!!游戏结束!!!')
quit()
# more game logic here
# ...
curses.endwin()
print('得分:' + str(score))The algorithm uses a board representation where each cell stores the distance to the food; board_reset initializes the board, and board_refresh performs a breadth‑first search to compute shortest paths.
Move selection functions include:
choose_shortest_safe_move – picks the direction with the smallest distance value.
choose_longest_safe_move – picks the direction with the largest distance (used when following the tail).
is_tail_inside – checks whether a safe path exists from head to tail.
follow_tail – forces the snake to chase its own tail.
any_possible_move – falls back to any legal direction.
A virtual snake is simulated with virtual_shortest_move and find_safe_way to ensure the AI only makes moves that keep a path to the food and avoid self‑collision.
Troubleshooting: On Windows, the curses window may be too small, causing _curses.error: curses function returned NULL . Enlarging the terminal or adjusting the window size resolves the issue.
Additional details cover generating new food, handling global variables, controlling speed with win.timeout() , and suggestions for extending the project (e.g., adding a second snake, separate maps, or more sophisticated AI).
References and further reading are provided, including links to the original AI‑Snake article, curses documentation, and related Python projects.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.