当贪吃蛇学会了“内卷”——我用AI让它自己卷自己

· · 算法·理论

难以想象ai军然那么喜欢标题党

引言:一条蛇的“觉醒”

那天,我像往常一样瘫在B站,刷着各种“AI教你打游戏”的视频。突然,一个标题映入眼帘:“用遗传算法训练贪吃蛇,它居然学会了绕圈圈!” 我承认,我被勾起了兴趣。

作为一个时常想搞点事情的程序员,我决定:为什么不自己写一个? 说干就干,我打开了Grok,噼里啪啦一顿操作,于是一个“贪吃蛇AI——神经进化版”诞生了。这可不是普通的贪吃蛇,它是一群会内卷、会突破、会记录高光时刻的蛇。

代码很长,但故事更有趣。如果你想直接看代码,可以拉到文末。但在那之前,让我先讲讲这条蛇的“奋斗史”。

1. 我们训练的不是蛇,是“卷王”

在这个世界里,有 200 条蛇同时出生在 (10 \times 10) 的地图上。它们没有老师,没有攻略,只有一套神经网络和一颗想要活下去的心。

它们的使命很简单:吃豆、长身体、别撞墙、别咬自己。 但随着时间的推移,它们发现——光是活着还不够,还得活得比别人强。

于是,我设计了一套“卷王评分系统”:

更“残酷”的是:如果某条蛇的长度超过了种群平均长度,它就会获得 1.2 倍的奖励分——这就是“内卷奖励机制”。

你以为这就完了?并没有。

如果某条蛇的原始适应度突破了历史最高,或者长度追平了历史最大长度——恭喜,直接获得 2 倍突破奖励!这就像考试考了满分,老师还给你发了双倍奖学金。

2. 饥饿是一种动力

为了让蛇们不那么“佛系”,我给它们加了一个饥饿机制:

也就是说,越到后期,竞争越激烈,饥饿越宽容,但对手也越强。

就像内卷的职场,前期拼体力,后期拼策略。

3. 记录高光时刻——每条蛇都是“电影主角”

这个系统还有一个我很喜欢的功能:每一代都会记录当前最优蛇的完整游戏过程。

如果某条蛇的长度 ≥ 历史最大长度,它的“高光时刻”就会被永久保存下来——成为 全局最优记录。

你可以随时按下 p 键,回放这条“蛇中传奇”的一生。看着它在棋盘上游走、觅食、躲避、成长,居然有一点点感动。

4. 两种训练模式,满足你的“窥探欲”

为了让训练更有趣,我设计了两种模式:

你想看蛇“跳舞”,还是看它“卷数据”?都可以。

5. 训练 1000 代之后,蛇变“佛系”了?

你可能会问:训练到后面,蛇会不会越来越强?

是的,但为了让它们不“过度探索”,我在 1000 代之后降低了变异率——从 20% 降到 5%,从 0.3 的变异幅度降到 0.1。

这时候,蛇们不再“乱试”,而是精细化调整策略。就像高手过招,不再花里胡哨,招招致命。

6. 数学公式里的“小心机”

这背后其实是一套 神经进化(Neuroevolution) 算法,用遗传算法来训练神经网络。

简单来说,每条蛇都有一个“大脑”(神经网络),结构如下:

[ \text{Input} \ (12) \rightarrow \text{Hidden} \ (16) \rightarrow \text{Output} \ (4) ]

输入是当前环境状态(食物方向、危险方向、当前方向等),输出是四个方向(上、下、左、右)的“偏好分”,选择最高的那个行动。

而适应度函数是:

[ \text{fitness} = (\text{length} \times 30 + \text{food} \times 25 + \text{steps} \times 0.1) \times \text{penalty} ]

再乘上那些“内卷奖励”和“突破奖励”。

看上去是冷冰冰的公式,但跑起来,你会看到一条条小蛇在屏幕上游走、挣扎、进化——像极了每一个努力生活的我们。

7. 运行你的“蛇群”

如果你也想亲眼看看这场“蛇界内卷”,只需要:

g++ -std=c++98 -O2 snake_ai_cpp98.cpp -o snake_ai98
./snake_ai98

然后你可以:

8. 完整代码(C++98 兼容版)

话不多说,直接上代码。你可以复制保存为 snake_ai_cpp98.cpp,然后编译运行。

/*
 * 贪吃蛇 AI 版本 - 神经进化 (Neuroevolution) - C++98 兼容版
 * 
 * 功能:
 *   - 10×10地图,200条蛇种群,1个豆子
 *   - 动态饥饿:≤150代=150步,>150代=250步
 *   - 适应度 = (长度*30 + 吃豆*25 + 步数*0.1) * 死亡惩罚 * 追平奖励 * 突破奖励
 *   - 长度高于种群平均的个体获得 1.2 倍适应度奖励
 *   - 长度追平或超过历史最大长度,或者原始适应度突破历史,均获得 2 倍突破奖励
 *   - 1000代后降低变异率(减少探索,加强利用)
 *   - 每个个体记录完整游戏帧
 *   - 记录长度≥历史最大长度→替换全局记录
 *   - 每代训练时只显示当前代最优的一条蛇
 *   - 按p:回放全局最优记录
 *   - 按x n:训练n代(显示蛇移动)
 *   - 按y n:快速训练n代(不显示蛇移动,每代只显示一行统计并清屏)
 *
 * 编译:g++ -std=c++98 -O2 snake_ai_cpp98.cpp -o snake_ai98
 */

#include <iostream>
#include <vector>
#include <deque>
#include <cmath>
#include <algorithm>
#include <string>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include <limits>
#include <sstream>

#ifdef _WIN32
  #include <windows.h>
#else
  #include <unistd.h>
#endif

using namespace std;

// ==================== 常量 ====================
const int WIDTH = 10;
const int HEIGHT = 10;
const int POP_SIZE = 200;
const int ELITE_COUNT = 20;
const int MAX_STEPS = 300;
const int INPUT_SIZE = 12;
const int HIDDEN_SIZE = 16;
const int OUTPUT_SIZE = 4;
const double MUTATION_RATE = 0.20;
const double MUTATION_SIGMA = 0.30;
const int DISPLAY_DELAY_MS = 110;
const int HUNGER_LIMIT_EARLY = 150;
const int HUNGER_LIMIT_LATE = 250;
const int EVAL_TRIALS = 3;

const int DX[4] = {0, 1, 0, -1};
const int DY[4] = {-1, 0, 1, 0};

// 全局统计
double global_best_fitness = 0.0;
double global_max_length = 3.0;
int g_hunger_limit = HUNGER_LIMIT_EARLY;

// 全局最优记录
vector<vector<string> > global_best_frames;

// ==================== 随机数工具 ====================
void seed_rng() {
    srand(static_cast<unsigned int>(time(NULL)));
}

double rand_double(double lo, double hi) {
    return lo + (hi - lo) * (static_cast<double>(rand()) / (RAND_MAX + 1.0));
}

int rand_int(int lo, int hi) {
    return lo + rand() % (hi - lo + 1);
}

double rand_normal(double mean, double sigma) {
    double u1 = rand_double(0.0001, 1.0);
    double u2 = rand_double(0.0, 1.0);
    double z = sqrt(-2.0 * log(u1)) * cos(2.0 * 3.141592653589793 * u2);
    return mean + sigma * z;
}

// ==================== 睡眠 / 清屏 ====================
void sleep_ms(int ms) {
#ifdef _WIN32
    Sleep(ms);
#else
    usleep(static_cast<useconds_t>(ms) * 1000);
#endif
}

void clear_screen() {
    system("cls");
}

// ==================== 点 ====================
struct Point {
    int x, y;
    bool operator==(const Point& o) const { return x == o.x && y == o.y; }
};

// ==================== 神经网络 ====================
class NeuralNet {
public:
    vector<double> weights;

    NeuralNet() {
        int size = INPUT_SIZE * HIDDEN_SIZE + HIDDEN_SIZE
                 + HIDDEN_SIZE * OUTPUT_SIZE + OUTPUT_SIZE;
        weights.resize(size);
        randomize();
    }

    void randomize(double lo = -1.0, double hi = 1.0) {
        for (size_t i = 0; i < weights.size(); ++i)
            weights[i] = rand_double(lo, hi);
    }

    vector<double> forward(const vector<double>& inputs) const {
        vector<double> hidden(HIDDEN_SIZE);
        for (int h = 0; h < HIDDEN_SIZE; ++h) {
            double sum = weights[INPUT_SIZE * HIDDEN_SIZE + h];
            for (int i = 0; i < INPUT_SIZE; ++i)
                sum += inputs[i] * weights[h * INPUT_SIZE + i];
            hidden[h] = tanh(sum);
        }

        vector<double> out(OUTPUT_SIZE);
        int w2_start = INPUT_SIZE * HIDDEN_SIZE + HIDDEN_SIZE;
        int b2_start = w2_start + HIDDEN_SIZE * OUTPUT_SIZE;
        for (int o = 0; o < OUTPUT_SIZE; ++o) {
            double sum = weights[b2_start + o];
            for (int h = 0; h < HIDDEN_SIZE; ++h)
                sum += hidden[h] * weights[w2_start + o * HIDDEN_SIZE + h];
            out[o] = sum;
        }
        return out;
    }

    int get_action(const vector<double>& state) const {
        vector<double> outs = forward(state);
        int best = 0;
        for (int i = 1; i < OUTPUT_SIZE; ++i)
            if (outs[i] > outs[best]) best = i;
        return best;
    }

    void mutate(double rate = MUTATION_RATE, double sigma = MUTATION_SIGMA) {
        for (size_t i = 0; i < weights.size(); ++i)
            if (rand_double(0.0, 1.0) < rate)
                weights[i] += rand_normal(0.0, sigma);
    }

    static NeuralNet crossover(const NeuralNet& a, const NeuralNet& b) {
        NeuralNet child;
        for (size_t i = 0; i < child.weights.size(); ++i)
            child.weights[i] = (rand_double(0.0, 1.0) < 0.5) ? a.weights[i] : b.weights[i];
        return child;
    }
};

// ==================== 游戏环境 ====================
class SnakeGame {
public:
    deque<Point> body;
    int dir;
    Point food;
    int steps;
    bool alive;
    int foods_eaten;
    int steps_since_last_food;
    int death_reason;

    SnakeGame() : death_reason(0) { reset(); }

    void reset() {
        body.clear();
        Point p;
        p.x = 5; p.y = 5; body.push_back(p);
        p.x = 4; p.y = 5; body.push_back(p);
        p.x = 3; p.y = 5; body.push_back(p);
        dir = 1;
        steps = 0;
        alive = true;
        foods_eaten = 0;
        steps_since_last_food = 0;
        death_reason = 0;
        place_food();
    }

    void place_food() {
        do {
            food.x = rand_int(0, WIDTH - 1);
            food.y = rand_int(0, HEIGHT - 1);
        } while (is_body(food));
    }

    bool is_body(const Point& p) const {
        for (deque<Point>::const_iterator it = body.begin(); it != body.end(); ++it)
            if (*it == p) return true;
        return false;
    }

    bool is_wall(const Point& p) const { return p.x < 0 || p.x >= WIDTH || p.y < 0 || p.y >= HEIGHT; }
    bool is_danger(const Point& p) const { return is_wall(p) || is_body(p); }

    Point next_pos(int d) const {
        Point h = body.front();
        Point r; r.x = h.x + DX[d]; r.y = h.y + DY[d];
        return r;
    }

    int turn_left(int d) const { return (d + 3) % 4; }
    int turn_right(int d) const { return (d + 1) % 4; }

    vector<double> get_state() const {
        vector<double> s(INPUT_SIZE, 0.0);
        Point head = body.front();
        s[0] = (food.x - head.x) / 9.0;
        s[1] = (food.y - head.y) / 9.0;

        int f = dir;
        int l = turn_left(dir);
        int r = turn_right(dir);
        s[2] = is_danger(next_pos(f)) ? 1.0 : 0.0;
        s[3] = is_danger(next_pos(l)) ? 1.0 : 0.0;
        s[4] = is_danger(next_pos(r)) ? 1.0 : 0.0;
        s[5 + dir] = 1.0;
        s[9] = static_cast<double>(body.size()) / 50.0;

        int dx = (food.x > head.x) ? (food.x - head.x) : (head.x - food.x);
        int dy = (food.y > head.y) ? (food.y - head.y) : (head.y - food.y);
        s[10] = static_cast<double>(dx + dy) / (WIDTH + HEIGHT);
        s[11] = static_cast<double>(steps_since_last_food) / 100.0;
        return s;
    }

    bool step(int action) {
        if (!alive) return false;
        if ((dir == 0 && action == 2) || (dir == 2 && action == 0) ||
            (dir == 1 && action == 3) || (dir == 3 && action == 1))
            action = dir;
        dir = action;

        Point nh = next_pos(dir);
        if (is_danger(nh)) {
            alive = false;
            death_reason = is_wall(nh) ? 1 : 2;
            return false;
        }

        body.push_front(nh);
        if (nh == food) {
            place_food();
            foods_eaten++;
            steps_since_last_food = 0;
        } else {
            body.pop_back();
            steps_since_last_food++;
        }

        steps++;
        if (steps >= MAX_STEPS) {
            alive = false;
            death_reason = 4;
        } else if (steps_since_last_food >= g_hunger_limit) {
            alive = false;
            death_reason = 3;
        }
        return alive;
    }

    int length() const { return static_cast<int>(body.size()); }

    vector<string> render_frame() const {
        vector<string> frame;
        string row;

        row = string(WIDTH + 2, '#');
        frame.push_back(row);

        for (int y = 0; y < HEIGHT; ++y) {
            row = "#";
            for (int x = 0; x < WIDTH; ++x) {
                Point p; p.x = x; p.y = y;
                if (!body.empty() && p == body.front())
                    row += "@";
                else if (is_body(p))
                    row += "o";
                else if (p == food)
                    row += "*";
                else
                    row += " ";
            }
            row += "#";
            frame.push_back(row);
        }

        row = string(WIDTH + 2, '#');
        frame.push_back(row);

        return frame;
    }
};

// ==================== 个体 ====================
struct Individual {
    NeuralNet nn;
    double fitness;
    int length_achieved;
    Individual() : fitness(0.0), length_achieved(0) {}
};

bool better_fitness(const Individual& a, const Individual& b) {
    return a.fitness > b.fitness;
}

// ==================== 评估 ====================
double evaluate_single_run(NeuralNet& nn, int& out_max_len) {
    SnakeGame game;
    int max_len = 3;
    while (game.alive) {
        vector<double> state = game.get_state();
        int action = nn.get_action(state);
        game.step(action);
        if (game.length() > max_len) max_len = game.length();
    }
    out_max_len = max_len;

    double base = max_len * 30.0 + game.foods_eaten * 25.0 + game.steps * 0.1;
    if (max_len == static_cast<int>(global_max_length)) base *= 1.5;

    double penalty = 1.0;
    switch (game.death_reason) {
        case 1: penalty = 0.6; break;
        case 2: penalty = 0.2; break;
        case 3: penalty = 0.5; break;
        case 4: penalty = 1.0; break;
        default: penalty = 0.5;
    }
    return base * penalty;
}

double evaluate(NeuralNet& nn, int& out_length) {
    double sum = 0.0;
    int best_len = 3;
    for (int t = 0; t < EVAL_TRIALS; ++t) {
        int len = 0;
        sum += evaluate_single_run(nn, len);
        if (len > best_len) best_len = len;
    }
    out_length = best_len;
    return sum / EVAL_TRIALS;
}

int record_game(NeuralNet& nn, vector<vector<string> >& out_frames) {
    SnakeGame game;
    int max_len = 3;
    out_frames.clear();

    out_frames.push_back(game.render_frame());

    while (game.alive) {
        vector<double> state = game.get_state();
        int action = nn.get_action(state);
        game.step(action);
        out_frames.push_back(game.render_frame());
        if (game.length() > max_len) max_len = game.length();
    }
    return max_len;
}

void evaluate_population(vector<Individual>& pop, int& best_idx) {
    best_idx = 0;
    double best_fit = -1e9;

    // 第一遍:计算原始适应度与长度
    for (size_t i = 0; i < pop.size(); ++i) {
        int len = 0;
        double raw = evaluate(pop[i].nn, len);
        pop[i].length_achieved = len;
        pop[i].fitness = raw;   // 暂存原始适应度
    }

    // 计算平均长度
    double sum_len = 0.0;
    for (size_t i = 0; i < pop.size(); ++i) {
        sum_len += pop[i].length_achieved;
    }
    double avg_len = sum_len / POP_SIZE;

    // 第二遍:应用奖励并记录全局最优
    for (size_t i = 0; i < pop.size(); ++i) {
        double raw = pop[i].fitness;

        // 突破奖励:适应度创新高 或 长度追平/超过历史最大长度
        if (raw > global_best_fitness || 
            pop[i].length_achieved >= static_cast<int>(global_max_length)) {
            pop[i].fitness = raw * 2.0;
            // 只有适应度真的更高时才更新全局最优适应度记录
            if (raw > global_best_fitness) {
                global_best_fitness = raw;
            }
        } else {
            pop[i].fitness = raw;
        }

        // 长度高于平均的奖励
        if (pop[i].length_achieved > avg_len) {
            pop[i].fitness *= 1.2;
        }

        if (pop[i].fitness > best_fit) {
            best_fit = pop[i].fitness;
            best_idx = i;
        }

        vector<vector<string> > individual_frames;
        int record_len = record_game(pop[i].nn, individual_frames);
        if (record_len >= static_cast<int>(global_max_length)) {
            global_max_length = static_cast<double>(record_len);
            global_best_frames = individual_frames;
        }
    }
}

// ==================== 进化操作 ====================
int tournament_select(const vector<Individual>& pop, int k = 3) {
    int best = rand_int(0, POP_SIZE - 1);
    for (int i = 1; i < k; ++i) {
        int cand = rand_int(0, POP_SIZE - 1);
        if (pop[cand].fitness > pop[best].fitness) best = cand;
    }
    return best;
}

void evolve(vector<Individual>& pop, int generation) {
    sort(pop.begin(), pop.end(), better_fitness);
    vector<Individual> new_pop(POP_SIZE);

    // 精英保留
    for (int i = 0; i < ELITE_COUNT; ++i)
        new_pop[i] = pop[i];

    // 动态变异参数:1000代后降低探索强度
    double rate  = MUTATION_RATE;
    double sigma = MUTATION_SIGMA;
    if (generation > 1000) {
        rate  = 0.05;
        sigma = 0.10;
    }

    // 交叉 + 变异
    for (int i = ELITE_COUNT; i < POP_SIZE; ++i) {
        int p1 = tournament_select(pop);
        int p2 = tournament_select(pop);
        new_pop[i].nn = NeuralNet::crossover(pop[p1].nn, pop[p2].nn);
        new_pop[i].nn.mutate(rate, sigma);
    }

    pop = new_pop;
}

// =================== 渲染 ====================
void render_frame(const vector<string>& frame, int gen, unsigned long total_eps,
                  double max_len, double avg_len, int cur_len,
                  const string& status = "") {
    clear_screen();
    cout << "========================================" << endl;
    cout << "   贪吃蛇 AI - 神经进化 (C++98 版)" << endl;
    cout << "========================================" << endl;
    cout << "代数:" << gen << " 训练次数:" << total_eps
         << " 最大长度:" << fixed << setprecision(0) << max_len
         << " 平均长度:" << setprecision(1) << avg_len
         << " 当前长度:" << cur_len
         << " 最优适应度:" << setprecision(2) << global_best_fitness
         << " 饥饿限制:" << g_hunger_limit;
    if (!status.empty()) cout << " " << status;
    cout << endl << endl;

    for (size_t i = 0; i < frame.size(); ++i) {
        cout << "  " << frame[i] << endl;
    }

    cout << endl;
    cout << "规则: 饥饿(" << HUNGER_LIMIT_EARLY << "→" << HUNGER_LIMIT_LATE
         << ") | 追平最长×1.5 | 突破(适应度↑或长度追平)×2 | 高于平均长度×1.2" << endl;
    if (status.empty())
        cout << "命令: p=回放最优记录, x n=训练n代(显示), y n=快速训练n代(不显示)" << endl;
}

// 实时展示一条蛇的运行
void showcase(NeuralNet& nn, int gen, unsigned long total_eps,
              double max_len, double avg_len) {
    SnakeGame game;
    while (game.alive) {
        vector<double> state = game.get_state();
        int action = nn.get_action(state);
        game.step(action);
        render_frame(game.render_frame(), gen, total_eps, max_len, avg_len,
                     game.length(), "[当前代最优]");
        cout.flush();
        sleep_ms(DISPLAY_DELAY_MS);
    }
}

// 回放全局最优记录
void replay_best(int gen, unsigned long total_eps, double max_len, double avg_len) {
    if (global_best_frames.empty()) {
        cout << "暂无全局最优记录。" << endl;
        sleep_ms(500);
        return;
    }
    for (size_t i = 0; i < global_best_frames.size(); ++i) {
        render_frame(global_best_frames[i], gen, total_eps, max_len, avg_len,
                     static_cast<int>(max_len), "[回放全局最优]");
        cout.flush();
        sleep_ms(DISPLAY_DELAY_MS);
    }
    sleep_ms(500);
}

// ==================== 动态饥饿限制 ====================
void update_hunger_limit(int generation) {
    if (generation > 150)
        g_hunger_limit = HUNGER_LIMIT_LATE;
    else
        g_hunger_limit = HUNGER_LIMIT_EARLY;
}

// ==================== 单行统计信息 ====================
void print_one_line_stats(int generation, unsigned long total_episodes, double avg_len) {
    clear_screen();
    cout << "代数:" << generation 
         << " 训练次数:" << total_episodes
         << " 最大长度:" << static_cast<int>(global_max_length)
         << " 平均长度:" << fixed << setprecision(1) << avg_len
         << " 当前长度:" << static_cast<int>(global_max_length)
         << " 最优适应度:" << setprecision(2) << global_best_fitness
         << " 饥饿限制:" << g_hunger_limit << endl;
}

// ==================== 主程序 ====================
int main() {
    seed_rng();

    vector<Individual> population(POP_SIZE);
    int generation = 0;
    unsigned long total_episodes = 0;
    double current_avg_length = 3.0;
    int best_idx = 0;

    cout << "贪吃蛇神经进化训练 (C++98) - 种群大小: " << POP_SIZE << endl;
    cout << "每代显示当前最优蛇,按 p 回放全局最优记录。" << endl;
    cout << "x n: 训练n代并显示蛇移动 | y n: 快速训练n代(每代一行统计)" << endl;
    sleep_ms(1500);

    // 初始代
    update_hunger_limit(1);
    evaluate_population(population, best_idx);

    double sum_len = 0.0;
    for (int i = 0; i < POP_SIZE; ++i) {
        sum_len += population[i].length_achieved;
    }
    current_avg_length = sum_len / POP_SIZE;
    total_episodes += POP_SIZE * EVAL_TRIALS;
    generation = 1;

    cout << "\n[代数: " << generation << "] 展示当前最优蛇..." << endl;
    sleep_ms(300);
    showcase(population[best_idx].nn, generation, total_episodes,
             global_max_length, current_avg_length);

    evolve(population, generation);

    // 主循环
    while (true) {
        update_hunger_limit(generation);

        cout << "\n[代数: " << generation << ",饥饿限制: " << g_hunger_limit
             << "] 输入命令 (p=回放, x n=训练并显示, y n=快速训练): ";
        cout.flush();

        char cmd;
        cin >> cmd;
        if (cin.fail()) {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            continue;
        }

        if (cmd == 'p' || cmd == 'P') {
            if (global_best_frames.empty()) {
                cout << "暂无全局最优记录。" << endl;
            } else {
                cout << "回放全局最优记录 (长度 " << static_cast<int>(global_max_length) << ")..." << endl;
                sleep_ms(300);
                replay_best(generation, total_episodes, global_max_length, current_avg_length);
            }
        }
        else if (cmd == 'x' || cmd == 'X') {
            int n = 0;
            cin >> n;
            if (cin.fail() || n <= 0) {
                cout << "无效的训练代数,请输入正整数。" << endl;
                cin.clear();
                cin.ignore(numeric_limits<streamsize>::max(), '\n');
                continue;
            }

            cout << "训练 " << n << " 代 (显示蛇移动)..." << endl;
            for (int i = 0; i < n; ++i) {
                update_hunger_limit(generation + 1);
                evaluate_population(population, best_idx);

                sum_len = 0.0;
                for (int j = 0; j < POP_SIZE; ++j) {
                    sum_len += population[j].length_achieved;
                }
                current_avg_length = sum_len / POP_SIZE;
                total_episodes += POP_SIZE * EVAL_TRIALS;
                generation++;

                cout << "代数:" << generation << " 展示当前最优蛇..." << endl;
                sleep_ms(200);
                showcase(population[best_idx].nn, generation, total_episodes,
                         global_max_length, current_avg_length);

                evolve(population, generation);
                // 额外突变仅在1000代之前进行
                if (generation % 5 == 0 && generation <= 1000) {
                    for (int j = 0; j < 2; ++j)
                        population[j].nn.mutate(0.05, 0.1);
                }
            }
            cout << "训练完成,当前代数: " << generation << endl;
        }
        else if (cmd == 'y' || cmd == 'Y') {
            int n = 0;
            cin >> n;
            if (cin.fail() || n <= 0) {
                cout << "无效的训练代数,请输入正整数。" << endl;
                cin.clear();
                cin.ignore(numeric_limits<streamsize>::max(), '\n');
                continue;
            }

            cout << "快速训练 " << n << " 代..." << endl;
            sleep_ms(500);

            for (int i = 0; i < n; ++i) {
                update_hunger_limit(generation + 1);
                evaluate_population(population, best_idx);

                sum_len = 0.0;
                for (int j = 0; j < POP_SIZE; ++j) {
                    sum_len += population[j].length_achieved;
                }
                current_avg_length = sum_len / POP_SIZE;
                total_episodes += POP_SIZE * EVAL_TRIALS;
                generation++;

                // 每代清屏并显示一行统计
                print_one_line_stats(generation, total_episodes, current_avg_length);

                evolve(population, generation);
                if (generation % 5 == 0 && generation <= 1000) {
                    for (int j = 0; j < 2; ++j)
                        population[j].nn.mutate(0.05, 0.1);
                }
            }
            cout << "\n快速训练完成! 当前代数: " << generation << endl;
        }
        else {
            cout << "未知命令 '" << cmd << "',请使用 p、x n 或 y n。" << endl;
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }
    }

    return 0;
}

写在最后:一条蛇的“哲学”

当我看这条蛇在屏幕上绕开墙壁、追逐食物、一次次“死掉”又重新进化时,我突然觉得——

这不仅仅是一个AI项目,更像是一场关于“生存、竞争、突破”的隐喻。

每一次死亡,都是一次学习。
每一次突破,都是一次重生。
而我们,不也是在各自的人生地图上,一点点进化着吗?

如果你喜欢这个故事,或者想亲自跑一跑这段代码,欢迎 Star 或 Fork。
毕竟,代码是理性的,但创造它的过程,是充满温度的。 🐍✨

管理球通过,本文有deepseek修改和润色,其实就是他写的

大神可以修改一下为啥是c++98当然是因为我的编译器是c++98

目前我的贪吃蛇 贪吃蛇 AI - 神经进化 (C++98 版)

代数:2500 训练次数:1500000 最大长度:22 平均长度:13.7 当前长度:22 最优适应度:1102.50 饥饿限制:250 [回放全局最优]

  ############  
  #oo        #  
  #oo        #  
  #oo        #  
  #oo        #  
  #oo     *  #  
  #oo        #  
  #oo        #  
  #oo        #  
  #ooo       #  
  #@oo       #  
  ############  

规则: 饥饿(150→250) | 追平最长×1.5 | 突破适应度×2

[代数: 2500,饥饿限制: 250] 输入命令 (p=回放, x n=训练并显示, y n=快速训练):