1

So I want to make a graphic game in console. I display graphics simply std::couting array of colored empty string like this:

while (1 == 1) {
  for (int i = 0; i < height * width; i++) {
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), pixels[i]);
    cout << pixel;
  }
  system("CLS");
}

array 'pixels' stores colors of each pixel, and string pixel = " ";

The thing is fps is really low, and You can see pixels 'blinking' and process of drawing is also so slow that you can see how each pixel is drown into the screen. Is there a way to increasy fps, or a better way to draw pixels?

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
Stanley
  • 142
  • 1
  • 12
  • 2
    What is the point of `1==1`? Just use `while (true)` – Aykhan Hagverdili Sep 15 '19 at 13:44
  • 3
    To speed things up a bit, don't use `system("cls")`. Instead use something like [this](https://stackoverflow.com/a/29260809/10147399) to go to the beginning and draw the next frame – Aykhan Hagverdili Sep 15 '19 at 13:47
  • @Ayxan seems resonable, ill give it a try! and about 1==1 im kidna new to C++ didnt know u can do that with true – Stanley Sep 15 '19 at 13:57
  • Maybe you can get the console window in a buffer and use that buffer to do your drawing. I saw someone doing it [here](https://youtu.be/xW8skO7MFYw) – kiner_shah Sep 15 '19 at 14:03

2 Answers2

1

The FPS of this approach is very slow since every system("CLS"); launches a new process with a command interpreter and execute the OS instruction CLS to clear the screen. This is an extremely high overhead.

Unfortunately, there is no standard C++ way to clear the screen. THis is platform dependent. You'd need to make it platform dependent using curses on linux platform and using console API of windows (see other question here with some more links to the API doc).

Christophe
  • 68,716
  • 7
  • 72
  • 138
0

Like how @Christophe said, system("CLS") is pretty slow and you would have to launch a new process every time you want to clear the screen.

The best approach I could think of is to clear the terminal using ANSI escape codes, there's a lot of resources about it, and also a lot of ways to clear the terminal. Here is an example:

#include <iostream>
#include <cstdio>

int main() {
    // Saves the current screen, then clears entire screen and places cursor at 0, 0
    std::cout << "\e[?47h << \e[2J" << "Press enter to continue..";
    //            ^          ^ Clear Screen
    //            | Save Screen
    getchar();

    // Restores saved screen
    std::cout << "\e[?47l" << std::endl;

    return 0;
}
AidanGamin
  • 67
  • 1
  • 7