I'm new to C++ and I'm trying to build a simple snake game that runs in the console.:
#include <iostream> #include <windows.h> #define WIDTH 30 #define HEIGHT 50 void board(){ // COORD coord; for(int i = 0; i < WIDTH; i++){ // Draw the right wall cout << "#"; for(int j = 0; j < HEIGHT; j++){ // coord.X = j; // coord.Y = i; // SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); // Draw the top && bottom wall if(i == 0 || i == WIDTH -1){ cout << "#"; } // Draw the the spaces in between if(i > 0 && i < WIDTH - 1 ){ cout << " "; } // Draw the left wall if(j == HEIGHT - 1){ cout << "#"; } } cout << "\n"; } } int main(){ while(true){ board(); } return 0; } While drawing the game board (walls and spaces) in an infinite loop, the entire console flickers continuously. I suspect this is because I'm re-drawing the whole board every time, but I'm not quite sure how to resolve the issue.
Could someone help me understand whyWhy does this flickering happenshappen and what strategies I might use to reduce or eliminate it? I've included my full code below:
#include <iostream> #include <windows.h> #define WIDTH 30 #define HEIGHT 50 void board(){ // COORD coord; for(int i = 0; i < WIDTH; i++){ // Draw the right wall cout << "#"; for(int j = 0; j < HEIGHT; j++){ // coord.X = j; // coord.Y = i; // SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); // Draw the top && bottom wall if(i == 0 || i == WIDTH -1){ cout << "#"; } // Draw the the spaces in between if(i > 0 && i < WIDTH - 1 ){ cout << " "; } // Draw the left wall if(j == HEIGHT - 1){ cout << "#"; } } cout << "\n"; } } int main(){ while(true){ board(); } return 0; } - Issue: The console flickers because the entire board is continuously redrawn redrawn in an infinite loop.
- Environment: Windows Console using <windows.h>.
- Goal: Improve the drawing method to reduce flickering, perhaps by only only updating parts of the screen or using a different technique for drawing drawing.
Any suggestions or resources on managing console output more efficiently in C++ would be greatly appreciated. Thank you!