跳到正文

剪贴板

剪贴板 izrwydl9

原文
剪贴板信息

剪贴板信息

收录
更新

snake(单人/双人)(决斗类)

C++
#include<bits/stdc++.h>
#include<conio.h>
#include<windows.h>
using namespace std;
#define pii pair<int,int>
#define fi first
#define se second
const int N=1e5;
const int width=60;
const int height=25;
const int MAX_FOOD=200;
const int MAX_STONE=15;
enum GameMode{
    TWO_PLAYER,
    VS_AI
};
GameMode gameMode;
vector<pii>snake1;
int dir1;
vector<pii>snake2;
int dir2;
bool isAI;
struct Food{
    int x,y;
    bool active;
    int value;
    int color;
};
vector<Food>foods;
struct Stone{
    int x,y;
    int size;
    int color;
};
vector<Stone>stones;
int score1,score2;
bool gameOver;
string winner;
int speed=80;
int colors[]={12,14,13,11,6,9,10,15,8,5};
int stoneColors[]={8,7,8,7,8};
int dx[]={0,0,-1,1};
int dy[]={-1,1,0,0};
map<pair<pii,pii>,vector<int>> pathCache;
void gotoxy(int x,int y){
    COORD coord;
    coord.X=x;
    coord.Y=y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}
void hideCursor(){
    CONSOLE_CURSOR_INFO cursor_info={1,0};
    SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cursor_info);
}
int checkFood(int x,int y){
    for(int i=0;i<foods.size();i++){
        if(foods[i].active&&foods[i].x==x&&foods[i].y==y)return i;
    }
    return -1;
}
bool checkStone(int x,int y){
    for(auto&s:stones){
        for(int i=0;i<s.size;i++){
            for(int j=0;j<s.size;j++){
                if(s.x+i==x && s.y+j==y)return 1;
            }
        }
    }
    return 0;
}
bool isSafe(int x,int y,vector<pii>&snake){
    if(x<0||x>=width||y<0||y>=height)return 0;
    if(checkStone(x,y))return 0;
    for(int i=0;i<snake.size()-1;i++){
        if(snake[i].fi==x&&snake[i].se==y)return 0;
    }
    return 1;
}
bool isDeadlyDirection(int dir, pii head, vector<pii>&snake){
    int nx=head.fi+dx[dir];
    int ny=head.se+dy[dir];
    return !isSafe(nx,ny,snake);
}
vector<int> findPath(pii start, pii target, vector<pii>&snake) {
    auto key = make_pair(start, target);
    if(pathCache.count(key)) return pathCache[key];
    queue<pii> q;
    map<pii,pii> parent;
    map<pii,int> dist;
    q.push(start);
    dist[start]=0;
    while(!q.empty()){
        pii cur=q.front(); q.pop();
        if(cur==target)break;
        for(int d=0;d<4;d++){
            int nx=cur.fi+dx[d];
            int ny=cur.se+dy[d];
            pii next={nx,ny};
            if(isSafe(nx,ny,snake) && !dist.count(next)){
                dist[next]=dist[cur]+1;
                parent[next]=cur;
                q.push(next);
            }
        }
    }
    vector<int> path;
    if(dist.count(target)){
        pii cur=target;
        while(cur!=start){
            pii par=parent[cur];
            if(par.fi<cur.fi) path.push_back(3);
            else if(par.fi>cur.fi) path.push_back(2);
            else if(par.se<cur.se) path.push_back(1);
            else if(par.se>cur.se) path.push_back(0);
            cur=par;
        }
        reverse(path.begin(), path.end());
    }
    pathCache[key]=path;
    return path;
}
double evaluateFood(Food& food, pii head, vector<pii>&snake){
    auto path=findPath(head,{food.x,food.y},snake);
    if(path.empty()) return -1;
    int dist=path.size();
    if(dist==0) return 1e9;
    return (double)food.value / dist;
}
int predictSafety(int startDir, pii head, vector<pii>&snake, int steps=8){
    int safeCount=0;
    pii cur=head;
    vector<pii> tempSnake=snake;
    for(int i=0;i<steps;i++){
        int nx=cur.fi+dx[startDir];
        int ny=cur.se+dy[startDir];
        if(nx<0||nx>=width||ny<0||ny>=height) break;
        if(checkStone(nx,ny)) break;
        bool selfCollision=0;
        for(int j=0;j<tempSnake.size()-1;j++){
            if(tempSnake[j].fi==nx&&tempSnake[j].se==ny){
                selfCollision=1;
                break;
            }
        }
        if(selfCollision) break;
        safeCount++;
        cur={nx,ny};
        tempSnake.push_back({nx,ny});
        tempSnake.erase(tempSnake.begin());
    }
    return safeCount;
}
void AI_move(){
    if(!isAI) return;
    pii head=snake2.back();
    if(isDeadlyDirection(dir2,head,snake2)){
        vector<pair<int,int>> safeDirs;
        for(int d=0;d<4;d++){
            if(d==(dir2^1)) continue;
            if(!isDeadlyDirection(d,head,snake2)){
                int steps=predictSafety(d,head,snake2);
                safeDirs.push_back({d,steps});
            }
        }
        if(!safeDirs.empty()){
            sort(safeDirs.rbegin(), safeDirs.rend(),
                 [](auto&a, auto&b){return a.se<b.se;});
            dir2=safeDirs[0].fi;
            return;
        }else{
            int reverseDir=dir2^1;
            if(!isDeadlyDirection(reverseDir,head,snake2)){
                dir2=reverseDir;
                return;
            }else{
                gameOver=1;
                winner="AI 撞墙了...";
                return;
            }
        }
    }
    vector<pair<double,int>> foodScores;
    for(int i=0;i<foods.size();i++){
        double score=evaluateFood(foods[i],head,snake2);
        if(score>0){
            foodScores.push_back({score,i});
        }
    }
    if(!foodScores.empty()){
        sort(foodScores.rbegin(), foodScores.rend());
        for(int idx=0;idx<min(3,(int)foodScores.size());idx++){
            int bestFood=foodScores[idx].second;
            auto path=findPath(head,{foods[bestFood].x,foods[bestFood].y},snake2);
            if(!path.empty() && !isDeadlyDirection(path[0],head,snake2)){
                dir2=path[0];
                return;
            }
        }
    }
    vector<pair<int,int>> safeDirs;
    for(int d=0;d<4;d++){
        if(d==(dir2^1)) continue;
        if(!isDeadlyDirection(d,head,snake2)){
            int steps=predictSafety(d,head,snake2);
            safeDirs.push_back({d,steps});
        }
    }
    if(!safeDirs.empty()){
        sort(safeDirs.rbegin(), safeDirs.rend(),
             [](auto&a, auto&b){return a.se<b.se;});
        dir2=safeDirs[0].fi;
    }else{
        gameOver=1;
        winner="AI 被困住了...";
    }
}
void spawnStone(){
    if(stones.size()>=MAX_STONE)return;
    int attempts=0;
    while(attempts<1000){
        int size=rand()%3+1;
        int x=rand()%(width-size+1);
        int y=rand()%(height-size+1);
        bool overlap=0;
        for(auto&s:stones){
            for(int i=0;i<s.size;i++){
                for(int j=0;j<s.size;j++){
                    for(int ii=0;ii<size;ii++){
                        for(int jj=0;jj<size;jj++){
                            if(s.x+i==x+ii && s.y+j==y+jj){
                                overlap=1;
                                goto outer;
                            }
                        }
                    }
                }
            }
        }
        outer:
        if(!overlap){
            for(int i=0;i<size;i++){
                for(int j=0;j<size;j++){
                    for(auto&s:snake1)if(s.fi==x+i&&s.se==y+j)overlap=1;
                    for(auto&s:snake2)if(s.fi==x+i&&s.se==y+j)overlap=1;
                }
            }
        }
        if(!overlap){
            for(int i=0;i<size;i++){
                for(int j=0;j<size;j++){
                    for(auto&f:foods)if(f.x==x+i&&f.y==y+j)overlap=1;
                }
            }
        }
        if(!overlap){
            Stone newStone;
            newStone.x=x;
            newStone.y=y;
            newStone.size=size;
            newStone.color=stoneColors[rand()%5];
            stones.push_back(newStone);
            break;
        }
        attempts++;
    }
}
void spawnFood(){
    if(foods.size()>=MAX_FOOD)return;
    int attempts=0;
    while(attempts<1000){
        int x=rand()%width;
        int y=rand()%height;
        bool onSnake=0;
        for(auto&s:snake1)if(s.fi==x&&s.se==y){onSnake=1;break;}
        if(!onSnake)for(auto&s:snake2)if(s.fi==x&&s.se==y){onSnake=1;break;}
        if(!onSnake)for(auto&f:foods)if(f.active&&f.x==x&&f.y==y){onSnake=1;break;}
        if(!onSnake && !checkStone(x,y)){
            Food newFood;
            newFood.x=x;
            newFood.y=y;
            newFood.active=1;
            newFood.value=rand()%20+5;
            newFood.color=colors[rand()%10];
            foods.push_back(newFood);
            break;
        }
        attempts++;
    }
}
void setup(){
    gameOver=0;
    winner="";
    srand(time(0));
    pathCache.clear();
    dir1=3;
    snake1.clear();
    snake1.push_back({10,10});
    dir2=3;
    snake2.clear();
    snake2.push_back({30,10});
    stones.clear();
    for(int i=0;i<5;i++)spawnStone();
    foods.clear();
    for(int i=0;i<5;i++)spawnFood();
    score1=score2=0;
}
void draw(){
    gotoxy(0,0);
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),14);
    if(gameMode==TWO_PLAYER){
        gotoxy(width/2-5,-1);
        cout<<"=== 双人对战模式 ===";
    }else{
        gotoxy(width/2-5,-1);
        cout<<"=== 对战AI模式 ===";
    }
    gotoxy(0,0);
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),7);
    for(int i=0;i<width+2;i++)cout<<"#";
    cout<<endl;
    for(int i=0;i<height;i++){
        for(int j=0;j<width;j++){
            if(j==0)cout<<"#";
            bool isStone=0;
            for(auto&s:stones){
                for(int ii=0;ii<s.size;ii++){
                    for(int jj=0;jj<s.size;jj++){
                        if(s.x+ii==j && s.y+jj==i){
                            SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),s.color);
                            cout<<"#";
                            isStone=1;
                            goto stone_done;
                        }
                    }
                }
            }
            stone_done:
            if(!isStone){
                bool isSnake1=0,isSnake2=0;
                int foodIdx=checkFood(j,i);
                for(auto&s:snake1){
                    if(s.fi==j&&s.se==i){
                        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),10);
                        cout<<"O";
                        isSnake1=1;
                        break;
                    }
                }
                if(!isSnake1){
                    for(auto&s:snake2){
                        if(s.fi==j&&s.se==i){
                            SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),13);
                            cout<<"O";
                            isSnake2=1;
                            break;
                        }
                    }
                }
                if(!isSnake1&&!isSnake2){
                    if(foodIdx!=-1){
                        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),foods[foodIdx].color);
                        cout<<"$";
                    }else{
                        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),7);
                        cout<<" ";
                    }
                }
            }
            SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),7);
            if(j==width-1)cout<<"#";
        }
        cout<<endl;
    }
    for(int i=0;i<width+2;i++)cout<<"#";
    cout<<endl;
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),10);
    cout<<"玩家1 (WASD): "<<score1<<"  ";
    if(gameMode==TWO_PLAYER){
        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),9);
        cout<<"玩家2 (方向键): "<<score2<<"  ";
    }else{
        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),13);
        cout<<"AI: "<<score2<<"  ";
    }
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),14);
    cout<<"食物: "<<foods.size()<<"/"<<MAX_FOOD<<"  ";
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),8);
    cout<<"石头: "<<stones.size()<<"/"<<MAX_STONE<<endl;
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),7);
    cout<<"按 ESC 返回菜单"<<endl;
}
void input(){
    if(_kbhit()){
        int key=_getch();
        if(key==27){
            gameOver=1;
            winner="返回菜单";
            return;
        }
        if(key==224){
            key=_getch();
            if(gameMode==TWO_PLAYER){
                switch(key){
                    case 72:if(dir2!=1)dir2=0;break;
                    case 80:if(dir2!=0)dir2=1;break;
                    case 75:if(dir2!=3)dir2=2;break;
                    case 77:if(dir2!=2)dir2=3;break;
                }
            }
        }else{
            switch(tolower(key)){
                case 'w':if(dir1!=1)dir1=0;break;
                case 's':if(dir1!=0)dir1=1;break;
                case 'a':if(dir1!=3)dir1=2;break;
                case 'd':if(dir1!=2)dir1=3;break;
                case 'p':gotoxy(0,height+4);system("pause");break;
            }
        }
    }
}
bool checkCollision(vector<pii>&snake,pii newHead){
    if(newHead.fi<0||newHead.fi>=width||newHead.se<0||newHead.se>=height)return 1;
    for(auto&s:snake)if(s==newHead)return 1;
    if(checkStone(newHead.fi,newHead.se))return 1;
    return 0;
}
void logic(){
    if(isAI)AI_move();
    pii newHead1=snake1.back();
    switch(dir1){
        case 0:newHead1.se--;break;
        case 1:newHead1.se++;break;
        case 2:newHead1.fi--;break;
        case 3:newHead1.fi++;break;
    }
    pii newHead2=snake2.back();
    switch(dir2){
        case 0:newHead2.se--;break;
        case 1:newHead2.se++;break;
        case 2:newHead2.fi--;break;
        case 3:newHead2.fi++;break;
    }
    if(newHead1==newHead2){
        gameOver=1;
        winner="平局!";
        return;
    }
    for(auto&s:snake2)if(newHead1==s){
        gameOver=1;
        winner=isAI?"AI 赢了!":"玩家2赢了!";
        return;
    }
    for(auto&s:snake1)if(newHead2==s){
        gameOver=1;
        winner="玩家1赢了!";
        return;
    }
    if(checkCollision(snake1,newHead1)){
        gameOver=1;
        winner=isAI?"AI 赢了!":"玩家2赢了!";
        return;
    }
    if(checkCollision(snake2,newHead2)){
        gameOver=1;
        winner="玩家1赢了!";
        return;
    }
    snake1.push_back(newHead1);
    int foodIdx1=checkFood(newHead1.fi,newHead1.se);
    if(foodIdx1!=-1){
        score1+=foods[foodIdx1].value;
        foods.erase(foods.begin()+foodIdx1);
    }else snake1.erase(snake1.begin());
    snake2.push_back(newHead2);
    int foodIdx2=checkFood(newHead2.fi,newHead2.se);
    if(foodIdx2!=-1){
        score2+=foods[foodIdx2].value;
        foods.erase(foods.begin()+foodIdx2);
    }else snake2.erase(snake2.begin());
    if(rand()%10<3)spawnFood();
    if(rand()%20<1)spawnStone();
    while(foods.size()<2)spawnFood();
}
void gameOverScreen(){
    system("cls");
    gotoxy(width/2-5,height/2-2);
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),12);
    cout<<"游戏结束";
    gotoxy(width/2-10,height/2);
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),10);
    cout<<"玩家1: "<<score1<<"  ";
    if(gameMode==TWO_PLAYER){
        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),9);
        cout<<"玩家2: "<<score2;
    }else{
        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),13);
        cout<<"AI: "<<score2;
    }
    gotoxy(width/2-10,height/2+2);
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),14);
    cout<<winner;
    gotoxy(width/2-12,height/2+4);
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),7);
    cout<<"按任意键返回菜单...";
    _getch();
}
void showMenu(){
    system("cls");
    gotoxy(width/2-10,height/2-5);
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),14);
    cout<<"=== 贪吃蛇 ===";
    gotoxy(width/2-10,height/2-2);
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),10);
    cout<<"1. 双人对战模式";
    gotoxy(width/2-10,height/2);
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),13);
    cout<<"2. 对战AI模式";
    gotoxy(width/2-10,height/2+2);
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),12);
    cout<<"3. 退出";
    gotoxy(width/2-15,height/2+5);
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),7);
    cout<<"请选择模式 (1-3): ";
    char ch=_getch();
    if(ch=='1'){
        gameMode=TWO_PLAYER;
        isAI=0;
    }else if(ch=='2'){
        gameMode=VS_AI;
        isAI=1;
    }else if(ch=='3')exit(0);
}
signed main(){
    hideCursor();
    while(1){
        showMenu();
        setup();
        while(!gameOver){
            draw();
            input();
            logic();
            Sleep(speed);
        }
        if(winner!="返回菜单")gameOverScreen();
    }
    CONSOLE_CURSOR_INFO cursor_info={1,1};
    SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cursor_info);
    system("cls");
    return 0;
}