简体   繁体   中英

How can I implement double buffering in my c++ game?

I have the problem of the flashing screen and I know that I need to use double buffering to fix it, but I don't know how and where to add it in my game. If for some reason I can't use it, is there any other way of reducing the flashing, because with the bigger maps it's getting worse. Here is part of the code:

    `const char HEIGHT=11, WIDTH=54;
     unsigned char maze[HEIGHT][WIDTH]={

     "##############################",
     "#  !#      # ###  ##         #",
     "# ### ###  # !!  ### ####### #        GAME OF THRANS",
     "#     #    #####  ## # !!  # #",
     "######## #  ##     # ####  # #      R-restart  Q-quit",
     "#  !   # #   #  #  #       # #            M-menu",
     "### ## # ### #  #! #### ######",
     "#   !# #  ## #  ####  # # !! #                  W",
     "# #### ## ## #   #    # #### #      Controls:  A-S-D",
     "#         ##   #   #         #",
     "##############################",
     };

     enemy1.x=14;
     enemy1.y=7;
     enemy2.x=22;
     enemy2.y=9;
     enemy3.x=10;
     enemy3.y=3;


      srand(time (NULL));

     while(on){

maze[ppy][ppx]=playerSprite;
maze[gpy][gpx]=goal;
maze[enemy1.y][enemy1.x]=enemy1.sprite;
maze[enemy2.y][enemy2.x]=enemy2.sprite;
maze[enemy3.y][enemy3.x]=enemy3.sprite;

for(int y=0; y<HEIGHT;y++){
    cout<<endl;
    for(int x=0;x<WIDTH;x++){
        cout<<maze[y][x];
    }
}
     for(;;){

randNum=rand()%randNumMax+1;
cout<<endl;


        movement=getch();
        switch (movement){
    case'w':
        if (maze[ppy-1][ppx]!='#' &&(maze[ppy-1][ppx]==' '||(maze[ppy-1][ppx]=='G','N','M','Y','!'))){
            maze[ppy][ppx]=' ';
            ppy--;
            moves++;
             if (maze[ppy][ppx]=='!'){
                Beep(400,150);
                points++;

             }`

You can't really do "double buffering" in the usual sense with standard C++ console io. With graphics, double buffering traditionally means doing all your rendering to an offscreen back-buffer and then switching it with the front-buffer during the v-blank to avoid flickering. There's nothing directly equivalent to that for console output in standard C++.

You could try something "in the spirit" of double buffering. Build up your final string using a stringstream rather than outputting directly to cout and then display the entire string in one go using one write to cout . This might reduce your flickering.

As a side note, you probably want to avoid using endl after each line of your output since it flushes the output stream which is not what you want. Use '\\n' instead and only use endl when you actually want to flush at the end of your 'frame'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM