跳到正文

科技·工程

好玩的贪吃蛇

songsongwqz约 15 分钟
原文
文章信息与版本

文章信息

收录
2026年5月5日
更新
2026年5月9日
篇幅
约 15 分钟

版本

  1. v1当前

我最今玩了几局贪吃蛇,本来只是想放松一下,结果越玩越上头。明明规则那么简单——吃豆子变长、撞墙或撞到自己就结束——可是真的玩起来才发现,这游戏一点都不简单。有时候明明快吃到豆子了,却被自己的身体堵住路;有时候地图看着很空,却一不小心就走进“死胡同”。

玩着玩着我突然冒出一个想法:人会犯错,那如果让 AI 来玩呢? 它会不会比我更聪明?会不会学会提前绕路、规划路线,而不是只看眼前的豆子?于是,我不只是“玩”贪吃蛇,而是开始训练一条会学习的贪吃蛇。(让ai帮我写一个程序)

这不是普通的贪吃蛇程序,而是加入了强化学习(Q-learning)和神经网络的 AI 贪吃蛇。它一开始和新手一样,经常乱撞、活不过几秒;但随着不断训练、反复尝试,它会慢慢知道它不能这样干于是他会…继续撞墙,我是觉得他很菜你们可以试试

C++
#include <bits/stdc++.h>
#include <windows.h>
#include <conio.h>
using namespace std;

const int N=10,M=10;
const int SNAKE_N=100;
const int FOOD_N=3;
double gamma=0.9,epsilon=1.0,epsMin=0.05,epsDecay=0.99995;
double outerProb=0.3;
int maxLen=0;
bool demo=0,protectMode=0;
int normalDelay=120,demoDelay=30;

struct Snake{
    vector<pair<int,int>> body,foods;
    int aliveTime,stepsWithoutFood,consecutiveFood,dir;
    bool alive;
};

vector<Snake> snakes(SNAKE_N);

void gotoxy(int x,int y){
    COORD c{(SHORT)x,(SHORT)y};
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),c);
}

struct NN{
    int in,hd,out;
    vector<vector<double>> w1,w2;
    vector<double>b1,b2;
    double lr=0.01;
    NN(int a,int b,int c):in(a),hd(b),out(c){
        w1.assign(in,vector<double>(hd));
        w2.assign(hd,vector<double>(out));
        b1.assign(hd,0);b2.assign(out,0);
        for(auto&v:w1){for(auto&x:v){x=(rand()%200-100)/100.0;}}
        for(auto&v:w2){for(auto&x:v){x=(rand()%200-100)/100.0;}}
    }
    vector<double> f(const vector<double>& x){
        vector<double> h(hd), o(out);
        for(int i=0;i<hd;i++){
            for(int j=0;j<in;j++){h[i]+=x[j]*w1[j][i];}
            h[i]=tanh(h[i]+b1[i]);
        }
        for(int i=0;i<out;i++){
            for(int j=0;j<hd;j++){o[i]+=h[j]*w2[j][i];}
            o[i]+=b2[i];
        }
        return o;
    }
    void train(const vector<double>& x,int a,double t){
        auto o=f(x);
        double d=t-o[a];
        for(int i=0;i<in;i++){for(int j=0;j<hd;j++){w1[i][j]+=lr*d*x[i];}}
        for(int i=0;i<hd;i++){for(int j=0;j<out;j++){w2[i][j]+=lr*d;}}
    }
};

NN nn(N*M+5,128,4),target(N*M+5,128,4);

void syncNet(){target=nn;}

void resetSnake(Snake&s){
    s.body={{N/2,M/2}};
    s.foods.clear();
    s.alive=1;
    s.aliveTime=0;
    s.stepsWithoutFood=0;
    s.consecutiveFood=0;
    s.dir=3;
}

void genFood(Snake&s){
    while(s.foods.size()<FOOD_N){
        int x,y;
        while(true){
            bool outer=((rand()%100)/100.0<outerProb);
            if(outer){
                if(rand()%2){x=0;}else{x=N-1;}
                y=rand()%M;
            }else{
                x=1+rand()%(N-2);
                y=1+rand()%(M-2);
            }
            bool ok=true;
            for(auto&p:s.body){if(p.first==x && p.second==y){ok=false;}}
            for(auto&f:s.foods){if(f.first==x && f.second==y){ok=false;}}
            if(ok){break;}
        }
        s.foods.push_back({x,y});
    }
}

// 永久禁止180°回头
bool forbidden180(Snake&s,int a){
    if((s.dir==0 && a==1) || (s.dir==1 && a==0) || (s.dir==2 && a==3) || (s.dir==3 && a==2)){return true;}
    return false;
}

// 蛇移动后是否会死
bool willDie(Snake&s,int a){
    int x=s.body[0].first,y=s.body[0].second;
    if(a==0){x--;} if(a==1){x++;} if(a==2){y--;} if(a==3){y++;}
    if(x<0 || x>=N || y<0 || y>=M){return true;}
    for(auto&p:s.body){if(p.first==x && p.second==y){return true;}}
    return false;
}

// 蛇看到自己身体每一节和豆子的位置
vector<double> getState(Snake&s){
    vector<double> st;
    for(int i=0;i<N;i++){
        for(int j=0;j<M;j++){
            double val=0;
            for(auto&p:s.body){if(p.first==i && p.second==j){val=1;}}
            for(auto&f:s.foods){if(f.first==i && f.second==j){val=2;}}
            st.push_back(val);
        }
    }
    st.push_back(s.body[0].first/(double)N);
    st.push_back(s.body[0].second/(double)M);
    st.push_back(s.stepsWithoutFood/350.0);
    st.push_back(s.aliveTime/50.0);
    st.push_back(s.body.size()/20.0);
    return st;
}

bool moveSnake(Snake&s,int a){
    if(forbidden180(s,a) || willDie(s,a)){ s.alive=0; return false;}
    s.dir=a;
    pair<int,int> h=s.body[0];
    if(a==0){h.first--;} if(a==1){h.first++;} if(a==2){h.second--;} if(a==3){h.second++;}
    s.body.insert(s.body.begin(),h);

    bool ate=false;
    for(int i=0;i<s.foods.size();i++){
        if(h==s.foods[i]){
            ate=true;
            s.foods.erase(s.foods.begin()+i);
            s.stepsWithoutFood=0;
            break;
        }
    }

    if(!ate){s.body.pop_back(); s.stepsWithoutFood++;}
    s.aliveTime++;
    if(s.stepsWithoutFood>=350){s.alive=0;}
    return ate;
}

double reward(Snake&s,bool ate){
    double r=0;
    if(!s.alive){r-=1;}
    if(s.aliveTime>=10){r+=4;}
    if(ate){ r+=10; s.consecutiveFood++; r+=s.consecutiveFood*0.5;}
    else{s.consecutiveFood=0;}
    if(s.body.size()==11){r+=50;}
    if(s.body.size()==51){r+=100;}
    return r;
}

void draw(){
    gotoxy(0,0);
    for(int j=0;j<M+2;j++){cout<<"#";}cout<<"\n";
    for(int i=0;i<N;i++){
        cout<<"#";
        for(int j=0;j<M;j++){
            char c='.';
            for(auto&f:snakes[0].foods){if(f.first==i && f.second==j){c='@';}}
            for(auto&p:snakes[0].body){if(p.first==i && p.second==j){c='O';}}
            cout<<c;
        }
        cout<<"#\n";
    }
    for(int j=0;j<M+2;j++){cout<<"#";}cout<<"\n";
    cout<<"Len:"<<snakes[0].body.size()<<" Max:"<<maxLen<<" eps:"<<epsilon
        <<"  Demo(Space)="<<demo<<" Protect(K/L)="<<protectMode<<"\n";
}

int main(){
    srand(time(0));
    cout<<"====== 贪吃蛇AI训练器 ======\n";
    cout<<"Space: 演示模式\n";
    cout<<"Z: 关闭展示\n";
    cout<<"P: 减少豆子刷在外圈概率\n";
    cout<<"Q: 正常豆子刷外圈概率\n";
    cout<<"K: 打开保护模式 L: 关闭保护模式\n";
    cout<<"蛇头永远禁止180度回头\n";
    cout<<"蛇看到自己身体每一节的位置\n";
    cout<<"按任意键开始训练...";
    _getch();
    system("cls");

    for(auto&s:snakes){resetSnake(s);}
    syncNet();
    static int step=0;

    while(true){
        if(GetAsyncKeyState(VK_SPACE)&0x8000){demo=1;}
        if(GetAsyncKeyState('Z')&0x8000){demo=0;}
        if(GetAsyncKeyState('P')&0x8000){outerProb=0.05;}
        if(GetAsyncKeyState('Q')&0x8000){outerProb=0.3;}
        if(GetAsyncKeyState('K')&0x8000){protectMode=1;}
        if(GetAsyncKeyState('L')&0x8000){protectMode=0;}

        for(auto&s:snakes){
            if(!s.alive){
                maxLen=max(maxLen,(int)s.body.size());
                resetSnake(s);
            }
            genFood(s);
            auto st=getState(s);

            vector<int> safe;
            for(int i=0;i<4;i++){
                if(protectMode && willDie(s,i)){continue;}
                safe.push_back(i);
            }
            if(safe.empty()){s.alive=0; continue;}

            int a;
            if((rand()%1000)/1000.0 < epsilon){
                a = safe[rand()%safe.size()];
            } else {
                auto q = nn.f(st);
                a = safe[0];
                for(int d : safe){if(q[d] > q[a]){a=d;}}
            }

            bool ate=moveSnake(s,a);
            double r=reward(s,ate);
            auto q2=target.f(getState(s));
            double t=r+gamma*(*max_element(q2.begin(),q2.end()));
            nn.train(st,a,t);
        }

        if(epsilon>epsMin){epsilon*=epsDecay;}
        step++;
        if(step%2000==0){syncNet();}
        if(demo){draw();}
        Sleep(demo?demoDelay:normalDelay);
    }
}

他开始会告诉你有保护模式建议别开不然蛇就得不到训练不开保护模式1小时大概13长度最高希望有人可以升级它,最后要讲的是这篇文章的作用推荐一道我的题U650699大家可以试试但是如何吧U换成P我很想了解一下希望大家可以告诉我

原文