So for my university homework we are supposed to make a simple game of a 2D map
with entities etc.
So I've figured a way of printing a map through it's dimensions and text formatting yet in our lessons it wasn't mentioned how we print on specific parts of the terminal. I've checked same questions but can't seem to get a solution.
Here is the code I use to print the map and make it's array. BLUE_B,STANDARD_B,OUTLINE and GREEN_B
are declared above for the sake of color enrichment. Also IF POSSIBLE I don't want to use OS specific commands unless it's completely necessary. I use VS Code for Windows, compile with g on WSL Ubuntu-20.04.
for (int row = 0; row < i; row ) {
cout << OUTLINE "##";
for (int column = 0; column < j; column ) {
int n = rand() % 10; // According to "rand()"'s value we print either green, blue, or trees
if (n >= 3) { // We've assigned more values to green, in order to be more possible to be printed
cout << GREEN_B " "
STANDARD_B;
map[row][column] = 1;
} else if (n == 0 || n == 1) {
cout << BLUE_B " "
STANDARD_B;
map[row][column] = 0;
} else if (n == 2) {
int tree = rand() % 2;
cout << TREES "<>"
STANDARD_B;
map[row][column] = 0;
}
}
cout << OUTLINE "##"
STANDARD_B << endl;
}
for (i = 0; i < j 2; i ) { // Bottom map border printing
cout << OUTLINE "##"
STANDARD_B;
}
CodePudding user response:
If I understand the question correctly, you might be looking for iomanip. It is just one way of doing it. You can use setw and setfill to position different text in different areas. You can set different options for different outputs.
CodePudding user response:
To move the text cursor to a specific line and column you need a “gotoxy”-style function.
Here is something that will work on both Linux terminals and the Windows Terminal. (It will not work on Windows Console without additional initialization help.)
#include <iostream>
const char * CSI = "\033[";
void gotoxy( int x, int y )
{
std::cout << CSI << (y 1) << ";" << (x 1) << "H";
}
Coordinates are (0,0) for the UL corner of the terminal. Here is a working example of use:
// continuing from above
#include <string>
int main()
{
// Clear a 40 x 10 box
for (int y = 0; y < 10; y )
{
gotoxy( 0, y );
std::cout << std::string( 40, ' ' );
}
// Draw our centered text
gotoxy( 14, 5 );
std::cout << "Hello there!";
// Go to bottom of box and terminate
gotoxy( 0, 10 );
std::cout.flush();
}
For your game
I suggest you move the cursor to HOME (0,0) and draw the changed parts of your gameboard each frame.
I suppose that if you are on a local computer and your gameboard is relatively simple, you could probably get away with a complete redraw each frame...
Are you sure there is no professor-supplied macro or command to move the cursor home? (...as he has supplied magic macros to change the output color)?