AI 贪吃蛇实验室

AI Snake Lab 是一个交互式强化学习沙盒,可在经典贪吃蛇游戏环境中试验 AI 智能体。它提供实时 Textual 终端用户界面(TUI)、灵活的经验回放数据库和模块化模型定义。

AI Snake Lab


🚀 功能

  • 🐍 经典贪吃蛇环境,可自定义网格及游戏规则。
  • 🧠 AI 智能体接口,支持不同模型架构(线性模型、RNN、CNN)。
  • 🎮 基于 Textual 的模拟器,实时显示游戏与指标。
  • 💾 SQLite 经验回放存储,保存帧、episode 与运行记录。
  • 🧩 实验元数据跟踪,包括模型、超参数、状态映射版本。
  • 📊 内置绘图,展示算力、分数及学习进展。

🧰 技术栈

组件 说明
Python 3.11+ 核心编程语言
Textual 终端 UI 框架
SQLite3 轻量级经验回放与实验存储
PyTorch(可选) 模型深度学习后端
Plotext / Matplotlib 可视化工具

🔄 动态训练

勾选 Dynamic Training(动态训练)后,每个 epoch 结束时执行的长时记忆训练次数会逐渐增加。随着 epoch 总数上升,每个 epoch 结束时调用 AIAgent:train_long_memory() 的次数也会增加,最高不超过 MAX_ADAPTIVE_TRAINING_LOOPS,根据以下计算,目前上限为 16:

    if self.dynamic_training():
        loops = max(
            1, min(self.epoch() // 250, DAIAgent.MAX_DYNAMIC_TRAINING_LOOPS)
        )
    else:
        loops = 1

    while loops > 0:
        loops -= 1
        self.train_long_memory()

🧩 Epsilon N

受 Richard Sutton 的《苦涩的教训》启发,Epsilon N 类可以直接替换传统的 Epsilon Greedy 算法。它针对每个分数建立独立的传统 Epsilon Greedy 实例。例如,当 AI 分数为 7 时,使用的是 self._epsilons[7] 中的实例。

下面的截图显示使用单一 Epsilon Greedy 实例,并启用动态训练时的最高分曲线。单实例 epsilon 算法很快收敛,但进步并不均匀。最高分曲线的突然跳跃说明,在 AI 完全掌握每个阶段之前,探索程度就已经下降了。

传统 Epsilon Greedy

下一张截图显示关闭动态训练、改用 Epsilon N 的最高分曲线。由于每个分数等级都有独立的 epsilon,Epsilon N 能维持局部探索。因此,AI 在进入下一阶段前可以逐步巩固学习成果,最高分曲线也更平滑、更加接近线性增长。

Epsilon N

如上所示,传统 Epsilon Greedy 的进步较慢,最高分曲线较早趋于平坦。相比之下,Epsilon N 让 AI 分别掌握每个分数等级,从而保持稳步提升。


💻 安装

这个项目已经发布在 PyPI 上,你可以通过 pip 安装 AI Snake Lab。

创建虚拟环境

python3 -m venv snake_venv
. snake_venv/bin/activate

安装 AI Snake Lab

激活 venv 虚拟环境之后:

pip install ai-snake-lab

▶️ 运行 AI Snake Lab

在已激活的 venv 环境中执行:

ai-snake-lab

⚠️ 限制

由于模拟运行在 Textual TUI 中,调整终端大小、重绘图表等操作可能轻微影响模拟时间。因此,即使重复运行,最高分也可能出现在略有差异的游戏编号上。这是预期行为,并不表示 AI 逻辑有问题。

如果你需要完全可重复的模拟运行,可以给我留言,我可以添加无界面模式,让模拟在 Textual 之外的独立进程中运行。


🙏 致谢

本项目最初基于 Patrick Loeber 的 YouTube 教程:Python + PyTorch + Pygame 强化学习:训练 AI 玩贪吃蛇。他的原始代码可以在 GitHub 上找到。感谢 Patrick!!!你太棒了!!!!本项目将原有 Pygame 和 Matplotlib 方案移植到了新的环境。

也感谢 Will McGugan 和 Textual 团队。Textual 真是个出色的框架。说到快速应用开发,从 Pygame + Matplotlib 移植到 Textual,居然不到一天就完成了。


🌟 灵感

创建一个 AI 智能体,让它自由尝试,再观察其表现,是一个令人惊叹的过程。有点像养育孩子,只是规模小得多、小得多、再小得多,至少今天还是如此!看 AI 驱动的贪吃蛇玩游戏,简直令人着迷。我总在想着还可以怎样改进它。感谢 Patrick Loeber 给了我一个探索 AI 的有趣项目。

我职业生涯的大部分时间都在担任 Linux 系统管理员,命令行是我的舒适区。我从未以程序员身份工作,更不用说前端开发人员了。Textual 这个用于构建丰富终端用户界面的框架,恰好适合我的风格。我第一次看到 Dolphie 时,简直惊呆了。内置、实时的 MySQL 指标图表,太精彩了!

Richard S. Sutton 也给了我很多启发。他对强化学习的思考是一场缓慢推进的革命。他批评现有 AI 领域过于专注于为特定任务设计专用 AI,完成任务就认为大功告成;我很认同这种看法。他关于能够持续进行非线性学习的 AI 智能体的愿景,仍是通往通用人工智能的重要前沿。


📚 技术文档


🔗 相关链接

2026

Git Automation

Some of you may have read my Git Battles post, where I talked about how I developed and a documented a Git workflow.

My blog in Simplified Chinese

I recently built MyCount to track website visitors to my projects. I found that that over 40% of my visitors were from China, and that 35% of those used a Ch...

MyCount: Website Analytics & Marketing

I have a future project in mind which will require a Dynamic DNS service. I created BMDynIP for that purpose. After building the service, I wanted a simple a...

Animating Ax3l Playing Snake

I’ve been tinkering with various incarnations of Patrick Loeber’s Train an AI to Play Snake tutorial for a while now. It’s my relaxing goto project that’s fu...

Dynamic DNS Service

This project started as a cron job and a flatfile and -honestly- that would work perfectly well for a small home setup. Say, two or three machines. I’m curre...

Local GeoIP Database

The Bear & Moose GeoIP Project provides an easy-to-use GeoIP service for your applications and for interactive lookups.

An LLM to organize my Movies

Our first TV was a small black-and-white thing where, on rare occasions, we’d watch Animal Kingdom. Then Beta and VHS came along, and you could watch them at...

From Prototype to Product (4/4)

Fr3d worked: It could talk to the Snake Lab, propose changes to the RNN configuration, run experiments, look at the results, and try again. It proved the ide...

Prompt Engineering 101 (3/4)

The Snake Lab had become a proper server, with a ZeroMQ API, configuration validation, a database, and a way to run experiments independently of the client. ...

The Evolution of Snake Lab (2/4)

In my last post, I setup a locally hosted LLM running on an old HP Z440 and wrote a crude little conversation loop. I generated random numbers, fed them to t...

Local LLM Writes Haikus (1/4)

This is part one of a four part blog series. In this post, I download, install and setup some software to prompt a local LLM to write haikus…

From Seed to Signal: AI FX

In the first post, AI FX was still mostly a seed: a repo, a PyPI package, and an idea about using automated FOREX tooling as a learning lab. Since then, the ...

Simulating the Power Grid

A potential client pointed me to Empowering the Energy Transition Through Fast and Flexible Network Simulation. The article describes an Open Source project,...

Delphi in a Day

I have a prospective client who runs a small group of technology businesses, at least one of which integrates with clients using the Delphi programming lan...

A Small Experiment: AI FX

I’ve spent some time around trading systemsL At Merrill Lynch, I supported the Order Audit Trail System (OATS), a compliance system required by NASDAQ. Its p...

Back to top ↑

2025

My Art on Etsy

I setup an Etsy Storefront to sell high quality, museum grade prints of some of my artwork.

Python systemctl Wrapper

I’ve been working on Db4E, my Monero deployment, operations and analytics platform. It uses Linux systemd to spin up manage Monero, P2Pool and XMRig instance...

AI Snake Lab

AI Snake Lab is an interactive reinforcement learning sandbox for experimenting with AI agents in a classic Snake Game environment — featuring a live Textual...

The Power of Pictures

You know that saying, “A picture is worth a thousand words.”? In programming, I’d argue it can be worth a thousand lines of code…

Caring About Constants

This post is about using constants in your code. Why it matters, what the benefits are and how you can do it well. I’m sad to say, I learned this the hard wa...

Why I Built Db4E

When I first started experimenting with Monero mining and self-hosted infrastructure, I did what everyone else does: I downloaded the Monero software, the P2...

Releasing with Git

Let me be honest: Git has punched me in the face more times than I can count. Every time I think I’ve got a smooth release flow down, Git yells, “Not so fast...

Documentation Matters

I was burned by opaque documentation: I’ve been building a modern terminal UI in Python using the excellent Textual framework. It’s sharp, fast, and honestly...

Textual Replaces ApexCharts

The original reporting system was a set of static dashboards built using GitHub Pages, JavaScript, and ApexCharts. It pulled data from my mining setup — via ...

Pivot to Textual

I’ve been deep in the trenches with my Db4E project — pulling together Monero mining infrastructure, MongoDB integration, and a bunch of orchestration magic....

Released Db4E SystemD

I recently published a small Python module to PyPI and GitHub: db4e-systemd, a lightweight wrapper around systemctl that lets you control services (start, st...

NIKU Farms

I received my order from NIKU Farms, YAY! It’s a meat delivery that my sister, Corinna Ghaznavi, gifted me this Christmas. Every two months I receive this am...

The Main Website

As part of my goal to be more visible in the world, I setup this domain i.e. https://osoyalce.com. I use it to publish information about the projects I’m wor...

Reviving the Blog

It’s been a while since I started and then abandoned this blog. My last post was in June of 2024!!

Changing the Blog Site’s Layout

I decided that I didn’t like the way that the main blog page looks. I am using GitHub to host the website and am using a fork of the jekyll/minima theme. My ...

Back to top ↑

2024

Aquaponics Update #1

It’s in the construction phase. I need to complete the water circulation process. I bought a fiber glass kit for this (and also to fix my kitchen sink!).

What I’m working on

The XMR Mining Farm complete with this eye-popping chart The Bear and Moose Knowledge Base My resume MyZODB - A Place to Store Everything

Back to top ↑