How to print big array without a delay
I would use an std::ostringstream
to build the output before printing to std::cout
and I'd use whatever control codes your terminal uses to clear the screen directly (or use a library, like pdcurses to do it). I'm not even sure you should clear the screen. Just putting the cursor top left seems better and it'll flicker less too.
Example:
void boardPrint(int rows, int columns, char** board) {
std::ostringstream os;
//os << "\033[H\033[2J"; // "home" + "cls" assuming you have an ansi terminal
os << "\033[H"; // just "home" (upper left corner)
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
os << board[i][j] << " ";
}
os << '\n';
}
// the output string is built, now print it
auto str = os.str();
std::cout.write(str.c_str(), static_cast<std::streamsize>(str.size()));
}
The actual loop could be rewritten to get a more stable updating by sleeping until a certain timepoint that you constantly add to. Like this:
auto tp = std::chrono::steady_clock::now();
while (game_is_on) {
boardPrint(rows + 2, columns + 2, board);
// ... other game logic ...
tp += std::chrono::milliseconds(10);
std::this_thread::sleep_until(tp);
}
I would also consider using a std::vector<std::string>
for the board and take that by const&
in the printing function.