Flappy Bird

· · 休闲·娱乐

请在Windows环境下编译

使用支持ANSI转义码的现代终端(例:Windows Terminal)

#include<bits/stdc++.h>
#include<unistd.h>
#include<conio.h>
#include<windows.h>
using namespace std;
char in[1<<20],out[1<<20],*p1=in,*p2=in,*p3=out;
#define pc(ch)(p3==out+(1<<20)&&write(1,p3=out,1<<20),*p3++=(ch))
class __flush__{public:~__flush__(){write(1,out,p3-out);write(1,"\x1b[0m",5);}}_;
namespace Putf{int pro=6;}
void put(const char*v){while(*v)pc(*v++);}
void put(char*v){while(*v)pc(*v++);}
template<typename T>
typename enable_if<is_integral<T>::value,void>::type put(T v){
    int SIZE=sizeof(v);
    if(!v)pc(48);
    else if(SIZE==2&&v==-32768)put("-32768");
    else if(SIZE==4&&v==-2147483648)put("-2147483648");
    else if(SIZE==8&&v==-9223372036854775807-1)put("-9223372036854775808");
    else{
        if(v<0)v=-v,pc(45);
        char buf[30]={};int cnt=0;
        while(v)buf[cnt++]=v%10^48,v/=10;
        while(cnt--)pc(buf[cnt]);
    }
}
template<typename T>
typename enable_if<is_floating_point<T>::value,void>::type putf(T v,const int&p){
    if(isnan(v)){put("nan");return;}
    if(isinf(v)){put("inf");return;}
    if(v<0)pc(45),v=-v;
    v=rint(v*pow(1e1,p));
    char buf[30]={};int cnt=0;
    while(v>0){
        T zh=floor(v/10);
        buf[cnt++]=48^int(v-zh*10),v=zh;
    }
    while(cnt<=p)buf[cnt++]=48;
    while(cnt--)pc(buf[cnt]),cnt==p&&p&&pc(46);
}
template<typename T>
typename enable_if<is_floating_point<T>::value,void>::type put(const T&v){putf(v,Putf::pro);}
void put(const char&v){pc(v);}
void put(const string&v){for(int i=0;i<v.size();i++)pc(v[i]);}
template<typename T,typename...R>
void put(const T&v,const R&...y){put(v),put(y...);}
void setColour(unsigned short r,unsigned short g,unsigned short b){
    put("\x1b[38;2;",r,';',g,';',b,'m');
}
void setColour(int rgb){
    setColour(rgb>>16,(rgb>>8)&255,rgb&255);
}
void setGround(unsigned short r,unsigned short g,unsigned short b){
    put("\x1b[48;2;",r,';',g,';',b,'m');
}
void setGround(int rgb){
    setGround(rgb>>16,(rgb>>8)&255,rgb&255);
}
void reset(){put("\x1b[0m");}
void resetColour(){put("\x1b[39m");}
void resetGround(){put("\x1b[49m");}
void flush(){write(1,out,p3-out);p3=out;}
void gotoxy(short x,short y){put("\x1b[",y+1,';',x+1,'H');}
void clrscr(){put("\x1b[2J\x1b[H");}
void hideCursor(){put("\x1b[?25l");}
void showCursor(){put("\x1b[?25h");}
const int GAME_WIDTH=40;
const int GAME_HEIGHT=16;
const int GAME_X=10;
const int GAME_Y=4;
const int BIRD_X=8;
const int TARGET_FPS=60;
const int FRAME_TIME_US=1000000/TARGET_FPS;
const double FALL_SPEED=0.3;
const double JUMP_FORCE=-0.9;
const char*DIFFICULTY_NAMES[]={
    "Easy","Normal","Regular","Hard","Nightmare","Hell","Are you sure?"
};
const int DIFFICULTY_COLORS[]={
    0x32CD32,0x00FF00,0xFFFF00,0xFFA500,0xFF4500,0xFF0000,0x8B0000
};
struct DifficultyParams{
    int pipeGap;
    int pipeSpacing;
    int pipeSpeed;
};
const DifficultyParams DIFFICULTY_SETTINGS[]={
    {9,20,3},
    {8,18,2},
    {7,16,2},
    {6,15,2},
    {5,14,1},
    {4,13,1},
    {3,12,1},
};
const int PIPE_WIDTH=3;
namespace Color{
    const int SKY_TOP=0x87CEEB;
    const int SKY_BOTTOM=0xB0E0E6;
    const int BIRD_BODY=0xFFD700;
    const int BIRD_BEAK=0xFF6347;
    const int BIRD_WING=0xFFA500;
    const int PIPE_MAIN=0x2E8B57;
    const int PIPE_LIGHT=0x3CB371;
    const int PIPE_DARK=0x006400;
    const int PIPE_CAP=0x228B22;
    const int GROUND=0x8B4513;
    const int GRASS=0x32CD32;
    const int WHITE=0xFFFFFF;
    const int BLACK=0x000000;
    const int GOLD=0xFFD700;
    const int RED=0xFF4444;
    const int GRAY=0x888888;
    const int TITLE_BG=0x1E3A5F;
    const int PAUSE_BG=0x2C2C2C;
}
const int FB_WIDTH=100;
const int FB_HEIGHT=26;
struct Pixel{
    char ch;
    int fg;
    int bg;
    Pixel():ch(' '),fg(-1),bg(-1){}
    Pixel(char c,int f,int b):ch(c),fg(f),bg(b){}
    bool operator!=(const Pixel&o)const{
        return ch!=o.ch||fg!=o.fg||bg!=o.bg;
    }
};
class FrameBuffer{
    Pixel cur[FB_HEIGHT][FB_WIDTH];
    Pixel prev[FB_HEIGHT][FB_WIDTH];
    bool forceUpdate;
public:
    FrameBuffer():forceUpdate(true){}
    void clear(){
        for(int y=0;y<FB_HEIGHT;y++)
            for(int x=0;x<FB_WIDTH;x++)
                cur[y][x]=Pixel();
    }
    void set(int x,int y,char ch,int fg=-1,int bg=-1){
        if(x>=0&&x<FB_WIDTH&&y>=0&&y<FB_HEIGHT)
            cur[y][x]=Pixel(ch,fg,bg);
    }
    void fillRect(int x1,int y1,int x2,int y2,char ch,int fg,int bg){
        for(int y=y1;y<=y2&&y<FB_HEIGHT;y++)
            for(int x=x1;x<=x2&&x<FB_WIDTH;x++)
                if(x>=0&&y>=0)cur[y][x]=Pixel(ch,fg,bg);
    }
    void text(int x,int y,const string&s,int fg=-1,int bg=-1){
        for(size_t i=0;i<s.size()&&x+(int)i<FB_WIDTH;i++)
            if(x+(int)i>=0)cur[y][x+i]=Pixel(s[i],fg,bg);
    }
    void textCenter(int y,const string&s,int fg=-1,int bg=-1){
        text((FB_WIDTH-s.size())/2,y,s,fg,bg);
    }
    void forceFull(){forceUpdate=true;}
    void render(){
        int lastFg=-2,lastBg=-2;
        int lastX=-2,lastY=-2;
        for(int y=0;y<FB_HEIGHT;y++){
            for(int x=0;x<FB_WIDTH;x++){
                if(!forceUpdate&&!(cur[y][x]!=prev[y][x]))continue;
                if(lastY!=y||lastX!=x-1)
                    gotoxy(x,y);
                if(cur[y][x].fg!=lastFg){
                    if(cur[y][x].fg>=0)setColour(cur[y][x].fg);
                    else resetColour();
                    lastFg=cur[y][x].fg;
                }
                if(cur[y][x].bg!=lastBg){
                    if(cur[y][x].bg>=0)setGround(cur[y][x].bg);
                    else resetGround();
                    lastBg=cur[y][x].bg;
                }
                pc(cur[y][x].ch);
                lastX=x;
                lastY=y;
            }
        }
        for(int y=0;y<FB_HEIGHT;y++)
            for(int x=0;x<FB_WIDTH;x++)
                prev[y][x]=cur[y][x];
        forceUpdate=false;
        flush();
    }
};
struct Bird{
    double y,velocity;
    Bird():y(GAME_HEIGHT/2),velocity(FALL_SPEED){}
    void jump(){velocity=JUMP_FORCE;}
    void update(){
        if(velocity<FALL_SPEED){
            velocity+=0.08;
            if(velocity>FALL_SPEED)velocity=FALL_SPEED;
        }
        y+=velocity;
    }
    void reset(){y=GAME_HEIGHT/2;velocity=FALL_SPEED;}
};
struct Pipe{
    int x,gapY;
    bool passed;
    Pipe(int startX):x(startX),gapY(0),passed(false){}
    void generate(int pipeGap){
        int halfGap=pipeGap/2;
        gapY=halfGap+1+rand()%(GAME_HEIGHT-pipeGap-1);
        passed=false;
    }
    bool collidesWith(int birdY,int pipeGap){
        if(x<=BIRD_X&&x+PIPE_WIDTH>BIRD_X){
            int halfGap=pipeGap/2;
            if(birdY<=gapY-halfGap||birdY>=gapY+halfGap)
                return true;
        }
        return false;
    }
};
class FlappyBird{
    Bird bird;
    vector<Pipe>pipes;
    int score,highScore;
    bool gameOver,started,paused;
    int difficulty;
    int frameCount;
    FrameBuffer fb;
public:
    FlappyBird():score(0),highScore(0),gameOver(false),started(false),
                   paused(false),difficulty(1),frameCount(0){
        srand(time(0));
    }
    int getPipeGap(){return DIFFICULTY_SETTINGS[difficulty].pipeGap;}
    int getPipeSpacing(){return DIFFICULTY_SETTINGS[difficulty].pipeSpacing;}
    int getPipeSpeed(){return DIFFICULTY_SETTINGS[difficulty].pipeSpeed;}
    void init(){
        bird.reset();
        pipes.clear();
        score=0;
        gameOver=false;
        started=false;
        paused=false;
        frameCount=0;
        fb.clear();
        fb.forceFull();
        Pipe p(GAME_WIDTH+5);
        p.generate(getPipeGap());
        pipes.push_back(p);
    }
    void update(){
        if(!started||gameOver||paused)return;
        frameCount++;
        bird.update();
        if(bird.y<0){
            bird.y=0;
            bird.velocity=FALL_SPEED;
        }
        if(bird.y>=GAME_HEIGHT){
            gameOver=true;
            if(score>highScore)highScore=score;
            return;
        }
        if(frameCount%getPipeSpeed()==0){
            for(auto&pipe:pipes){
                pipe.x--;
            }
        }
        for(auto&pipe:pipes){
            if(pipe.collidesWith((int)bird.y,getPipeGap())){
                gameOver=true;
                if(score>highScore)highScore=score;
                return;
            }
            if(!pipe.passed&&pipe.x+PIPE_WIDTH<BIRD_X){
                pipe.passed=true;
                score++;
            }
        }
        while(!pipes.empty()&&pipes[0].x+PIPE_WIDTH<0)
            pipes.erase(pipes.begin());
        if(pipes.empty()||pipes.back().x<GAME_WIDTH-getPipeSpacing()){
            Pipe p(GAME_WIDTH);
            p.generate(getPipeGap());
            pipes.push_back(p);
        }
    }
    void drawBorder(){
        int left=GAME_X-2;
        int right=GAME_X+GAME_WIDTH*2+1;
        int top=GAME_Y-1;
        int bottom=GAME_Y+GAME_HEIGHT;
        for(int y=top;y<=bottom;y++){
            fb.set(left,y,'|',Color::GRAY,-1);
            fb.set(right,y,'|',Color::GRAY,-1);
        }
        for(int x=left;x<=right;x++){
            fb.set(x,top,'-',Color::GRAY,-1);
            fb.set(x,bottom,'-',Color::GRAY,-1);
        }
        fb.set(left,top,'+',Color::GRAY,-1);
        fb.set(right,top,'+',Color::GRAY,-1);
        fb.set(left,bottom,'+',Color::GRAY,-1);
        fb.set(right,bottom,'+',Color::GRAY,-1);
    }
    void drawBackground(){
        for(int y=0;y<GAME_HEIGHT;y++){
            int screenY=GAME_Y+y;
            int bg=Color::SKY_TOP;
            for(int x=0;x<GAME_WIDTH;x++){
                int screenX=GAME_X+x*2;
                fb.set(screenX,screenY,' ',-1,bg);
                fb.set(screenX+1,screenY,' ',-1,bg);
            }
        }
        int groundY=GAME_Y+GAME_HEIGHT;
        for(int x=0;x<GAME_WIDTH;x++){
            int screenX=GAME_X+x*2;
            fb.set(screenX,groundY,'=',Color::GRASS,Color::GROUND);
            fb.set(screenX+1,groundY,'=',Color::GRASS,Color::GROUND);
        }
    }
    void drawBird(){
        int y=(int)bird.y;
        if(y<0)y=0;
        if(y>=GAME_HEIGHT)y=GAME_HEIGHT-1;
        int screenX=GAME_X+BIRD_X*2;
        int screenY=GAME_Y+y;
        int bg=Color::SKY_TOP;
        fb.set(screenX,screenY,'(',Color::BIRD_BODY,bg);
        fb.set(screenX+1,screenY,'o',Color::BLACK,bg);
        fb.set(screenX+2,screenY,')',Color::BIRD_BODY,bg);
        if(y+1<GAME_HEIGHT){
            fb.set(screenX+1,screenY+1,'>',Color::BIRD_WING,bg);
        }
        fb.set(screenX+3,screenY,'>',Color::BIRD_BEAK,bg);
    }
    void drawPipe(const Pipe&pipe){
        if(pipe.x<-PIPE_WIDTH||pipe.x>=GAME_WIDTH)return;
        int pipeGap=getPipeGap();
        int halfGap=pipeGap/2;
        int gapTop=pipe.gapY-halfGap;
        int gapBottom=pipe.gapY+halfGap;
        int screenX=GAME_X+pipe.x*2;
        for(int y=0;y<gapTop&&y<GAME_HEIGHT;y++){
            int screenY=GAME_Y+y;
            fb.set(screenX,screenY,'[',Color::PIPE_LIGHT,Color::PIPE_MAIN);
            fb.set(screenX+1,screenY,'#',Color::PIPE_LIGHT,Color::PIPE_MAIN);
            fb.set(screenX+2,screenY,'#',Color::PIPE_LIGHT,Color::PIPE_MAIN);
            fb.set(screenX+3,screenY,']',Color::PIPE_LIGHT,Color::PIPE_MAIN);
        }
        if(gapTop>0&&gapTop<=GAME_HEIGHT){
            int capY=GAME_Y+gapTop;
            for(int i=0;i<6;i++){
                int x=screenX-1+i;
                char c=(i==0||i==5)?'|':'=';
                fb.set(x,capY-1,c,Color::WHITE,Color::PIPE_CAP);
            }
        }
        if(gapBottom<GAME_HEIGHT){
            int capY=GAME_Y+gapBottom;
            for(int i=0;i<6;i++){
                int x=screenX-1+i;
                char c=(i==0||i==5)?'|':'=';
                fb.set(x,capY,c,Color::WHITE,Color::PIPE_CAP);
            }
        }
        for(int y=gapBottom;y<GAME_HEIGHT;y++){
            int screenY=GAME_Y+y;
            fb.set(screenX,screenY,'[',Color::PIPE_LIGHT,Color::PIPE_MAIN);
            fb.set(screenX+1,screenY,'#',Color::PIPE_LIGHT,Color::PIPE_MAIN);
            fb.set(screenX+2,screenY,'#',Color::PIPE_LIGHT,Color::PIPE_MAIN);
            fb.set(screenX+3,screenY,']',Color::PIPE_LIGHT,Color::PIPE_MAIN);
        }
    }
    void drawUI(){
        string title="FLAPPY BIRD";
        int titleX=(FB_WIDTH-title.size())/2;
        fb.text(titleX,1,title,Color::GOLD,Color::TITLE_BG);
        string scoreStr="Score: "+to_string(score);
        fb.text(GAME_X,2,scoreStr,Color::WHITE,-1);
        string bestStr="Best: "+to_string(highScore);
        fb.text(GAME_X+30,2,bestStr,Color::GOLD,-1);
        string diffStr="Difficulty: "+string(DIFFICULTY_NAMES[difficulty]);
        fb.text(GAME_X+55,2,diffStr,DIFFICULTY_COLORS[difficulty],-1);
    }
    void drawStartScreen(){
        fb.clear();
        drawBackground();
        drawBorder();
        drawUI();
        int centerX=GAME_X+GAME_WIDTH;
        fb.textCenter(GAME_Y+5,"Press SPACE to Start",Color::WHITE,Color::SKY_TOP);
        fb.textCenter(GAME_Y+7,"SPACE / W / UP to Flap",Color::WHITE,Color::SKY_TOP);
        fb.textCenter(GAME_Y+9,"ESC to Pause  |  Q to Quit",Color::GRAY,Color::SKY_TOP);
        int birdX=centerX-2;
        int birdY=GAME_Y+GAME_HEIGHT/2;
        fb.set(birdX,birdY,'(',Color::BIRD_BODY,Color::SKY_TOP);
        fb.set(birdX+1,birdY,'o',Color::BLACK,Color::SKY_TOP);
        fb.set(birdX+2,birdY,')',Color::BIRD_BODY,Color::SKY_TOP);
        fb.set(birdX+3,birdY,'>',Color::BIRD_BEAK,Color::SKY_TOP);
    }
    void drawPauseScreen(){
        int centerX=GAME_X+GAME_WIDTH;
        int centerY=GAME_Y+GAME_HEIGHT/2;
        int boxLeft=centerX-16;
        int boxRight=centerX+15;
        int boxTop=centerY-7;
        int boxBottom=centerY+7;
        fb.fillRect(boxLeft,boxTop,boxRight,boxBottom,' ',-1,Color::PAUSE_BG);
        for(int x=boxLeft;x<=boxRight;x++){
            fb.set(x,boxTop,'=',Color::GOLD,Color::PAUSE_BG);
            fb.set(x,boxBottom,'=',Color::GOLD,Color::PAUSE_BG);
        }
        for(int y=boxTop;y<=boxBottom;y++){
            fb.set(boxLeft,y,'|',Color::GOLD,Color::PAUSE_BG);
            fb.set(boxRight,y,'|',Color::GOLD,Color::PAUSE_BG);
        }
        fb.textCenter(centerY-6,"=== PAUSED ===",Color::GOLD,Color::PAUSE_BG);
        fb.textCenter(centerY-4,"Select Difficulty:",Color::WHITE,Color::PAUSE_BG);
        for(int i=0;i<=6;i++){
            string line=(i==difficulty?"> ":"  ")+
                          to_string(i)+": "+DIFFICULTY_NAMES[i]+
                          (i==difficulty?" <":"");
            fb.textCenter(centerY-2+i,line,DIFFICULTY_COLORS[i],
                          i==difficulty?0x444444:Color::PAUSE_BG);
        }
        fb.textCenter(centerY+6,"0-6 to Change | ESC Resume",Color::GRAY,Color::PAUSE_BG);
    }
    void drawGameOver(){
        int centerX=GAME_X+GAME_WIDTH;
        int centerY=GAME_Y+GAME_HEIGHT/2;
        int boxLeft=centerX-12;
        int boxRight=centerX+11;
        int boxTop=centerY-3;
        int boxBottom=centerY+3;
        fb.fillRect(boxLeft,boxTop,boxRight,boxBottom,' ',-1,Color::BLACK);
        for(int x=boxLeft;x<=boxRight;x++){
            fb.set(x,boxTop,'=',Color::RED,Color::BLACK);
            fb.set(x,boxBottom,'=',Color::RED,Color::BLACK);
        }
        for(int y=boxTop;y<=boxBottom;y++){
            fb.set(boxLeft,y,'|',Color::RED,Color::BLACK);
            fb.set(boxRight,y,'|',Color::RED,Color::BLACK);
        }
        fb.textCenter(centerY-2,"GAME OVER",Color::RED,Color::BLACK);
        string scoreText="Score: "+to_string(score);
        fb.textCenter(centerY,scoreText,Color::WHITE,Color::BLACK);
        if(score>=highScore&&score>0){
            fb.textCenter(centerY+1,"NEW RECORD!",Color::GOLD,Color::BLACK);
        }
        fb.textCenter(centerY+2,"SPACE to Retry",Color::GRAY,Color::BLACK);
    }
    void render(){
        fb.clear();
        drawBackground();
        drawBorder();
        for(const auto&pipe:pipes)
            drawPipe(pipe);
        drawBird();
        drawUI();
        if(paused)
            drawPauseScreen();
        else if(gameOver)
            drawGameOver();
        fb.render();
    }
    void run(){
        init();
        hideCursor();
        SetConsoleOutputCP(65001);
        drawStartScreen();
        fb.render();
        bool prevPress=false;
        while(!started){
            bool press=(GetAsyncKeyState(VK_SPACE)&0x8000)||
                         (GetAsyncKeyState('W')&0x8000)||
                         (GetAsyncKeyState(VK_UP)&0x8000);
            if(_kbhit()){
                int ch=_getch();
                if(ch=='q'||ch=='Q'){
                    showCursor();
                    clrscr();
                    reset();
                    flush();
                    return;
                }
            }
            if(press&&!prevPress){
                started=true;
                bird.jump();
                fb.forceFull();
            }
            prevPress=press;
            usleep(10000);
        }
        while((GetAsyncKeyState(VK_SPACE)&0x8000)||
               (GetAsyncKeyState('W')&0x8000)||
               (GetAsyncKeyState(VK_UP)&0x8000)){
            usleep(5000);
        }
        LARGE_INTEGER freq,lastT,curT;
        QueryPerformanceFrequency(&freq);
        QueryPerformanceCounter(&lastT);
        prevPress=false;
        while(true){
            QueryPerformanceCounter(&curT);
            bool press=(GetAsyncKeyState(VK_SPACE)&0x8000)||
                         (GetAsyncKeyState('W')&0x8000)||
                         (GetAsyncKeyState(VK_UP)&0x8000);
            if(_kbhit()){
                int ch=_getch();
                if(ch=='q'||ch=='Q')break;
                if(ch==27){
                    paused=!paused;
                    fb.forceFull();
                    if(paused){
                        render();
                        while(paused){
                            if(_kbhit()){
                                int c=_getch();
                                if(c==27){
                                    paused=false;
                                    fb.forceFull();
                                }else if(c>='0'&&c<='6'){
                                    difficulty=c-'0';
                                    render();
                                }else if(c=='q'||c=='Q'){
                                    showCursor();
                                    clrscr();
                                    reset();
                                    flush();
                                    return;
                                }
                            }
                            usleep(10000);
                        }
                    }
                }
            }
            if(press&&!prevPress){
                if(gameOver){
                    init();
                    started=true;
                    bird.jump();
                    fb.forceFull();
                }else if(!paused){
                    bird.jump();
                }
            }
            prevPress=press;
            update();
            render();
            QueryPerformanceCounter(&curT);
            long long elapsed=(curT.QuadPart-lastT.QuadPart)*1000000/freq.QuadPart;
            if(elapsed<FRAME_TIME_US)
                usleep(FRAME_TIME_US-elapsed);
            QueryPerformanceCounter(&lastT);
        }
        showCursor();
        clrscr();
        reset();
        flush();
    }
};
signed main(){
    SetConsoleOutputCP(65001);
    FlappyBird game;
    game.run();
    return 0;
}