贪吃蛇

· · 个人记录

#include<bits/stdc++.h>
#include <conio.h>
#include <windows.h>
#include <thread>
#include <chrono>
#define zxb(VK_NONAME) ((GetAsyncKeyState(VK_NONAME) & 0x8000) ? 1:0)
using namespace std;
void hide(){
    CONSOLE_CURSOR_INFO cursor_info={1,0};
    SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cursor_info);
}
void gotoxy(int x,int y){
    COORD pos={(SHORT)x,(SHORT)y};
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);
}
const int N=20;
int x=N/2,y=N/2;
queue<pair<int,int> > q;
int a[N+10][N+10];
void update(){
    int cnt=rand()%4;
    while(cnt--){
        int xx=rand()%(N+1),yy=rand()%(N+1);
        while(a[xx][yy]){
            xx=rand()%(N+1),yy=rand()%(N+1);
        }
        a[xx][yy]=2;
        gotoxy(yy,xx);
        cout<<'@';
    }
}
void del(){
    auto u=q.front();
    q.pop();
    a[u.first][u.second]=0;
    gotoxy(u.second,u.first);
    cout<<'.';
}
void move_down(){
    if(x>=N) return ;
    ++x;
    if(a[x][y]!=2) del();
    else update();
    a[x][y]=1;
    gotoxy(y,x);
    cout<<'x';
    q.push({x,y});
}
void move_l(){
    if(y<=0) return ;
    --y;
    if(a[x][y]!=2) del();
    else update();
    a[x][y]=1;
    gotoxy(y,x);
    cout<<'x';
    q.push({x,y});
}
void move_r(){
    if(y>=N) return ;
    ++y;
    if(a[x][y]!=2) del();
    else update();
    a[x][y]=1;
    gotoxy(y,x);
    cout<<'x';
    q.push({x,y});
}
void move_up(){
    if(x<=0) return ;
    --x;
    if(a[x][y]!=2) del();
    else update();
    a[x][y]=1;
    gotoxy(y,x);
    cout<<'x';
    q.push({x,y});
}
void print(){
    gotoxy(0,0);
    for(int i=0;i<=N;i++){
        for(int j=0;j<=N;j++){
            if(a[i][j]==0){
                cout<<'.';
            }else if(a[i][j]==1){
                cout<<'x';
            }else{
                cout<<'@';
            }
        }
        cout<<'\n';
    }
    cout<<"Use W,A,S,D to move. Press 'q' to quit."<<'\n';
}
bool flag=1;
int main(){
    srand(time(0));hide();
    a[x][y]=1;
    q.push({x,y});
    update();
    print();
    while(flag){
        while(1){
            if(zxb('Q')){ flag=0;break;}
            if(zxb('W')){ move_up();break;}
            if(zxb('A')){ move_l();break;}
            if(zxb('S')){ move_down();break;}
            if(zxb('D')){ move_r();break;}
        }
        this_thread::sleep_for(chrono::milliseconds(50));
    }
    return 0;
}