Turning a single letter into a different color using the console

Im trying to make my "characters" in my console game stand out more, these characters move through a 2d array using keys and can sometimes blend into the other letters in the map. I want to change the color of these single characters to Red and Blue, but i have no idea on how to go about doing that. Heres an outline of what my map will do:


I I I I
I I B I
I I I I


W is pressed
last position of B set back to the original character
Position above B is set to the character B


I I B I
I I I I
I I I I

if it makes any difference i use windows 7 and code::blocks

Thanks if you can help!
Last edited on
The setColor function will set the color that the console will use when printing characters.

You will have to use the setColor function for each character before you print them.
The OP will need a "set color" function.

1
2
3
4
5
6
7
8
9
10
#define NOMINMAX
#include <windows.h>

void SetColor( int fg )
  {
  CONSOLE_SCREEN_BUFFER_INFO csbi;
  HANDLE hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
  GetConsoleScreenBufferInfo( hstdout, &csbi );
  SetConsoleTextAttribute( hstdout, (csbi.wAttributes & 0xF0) | (fg & 0x0F) );
  }

Hope this helps.
Thanks guys! so will this function set all characters after i use the function to the color? so i would need to use the function for the character, then change the color back to default? Please excuse my lack of intelligence regarding win32, I've never gotten around to actually learning any of it yet.
Er, no, this makes a permanent change to the text foreground color. You need to change the color back to the default yourself.

Line 8 above gets information about the current text colors ("attributes"). It is probably worth your time to use that function at the very beginning of your program, and then restore the colors using SetConsoleTextAttribute() before your program terminates.

Colors are packed into a single byte: the low nibble is the foreground color and the high nibble is the background color. It usually defaults to 0x07, but the Windows Console lets your users adjust that however they want, so you should avoid making any assumptions in your code. (Just as I did above -- line 9 preserves the current background color while changing the foreground color.)

Color values for each nibble are some combination of:
- bit 0 - blue
- bit 1 - green
- bit 2 - red
- bit 3 - intensity (brighter color)

Hope this helps.
Topic archived. No new replies allowed.