Home > Blockchain >  How to color specific regions of an array
How to color specific regions of an array

Time:09-15

I know the color chart and I know a little about how to use it, but...
How to color specific regions of an array, like the rocket's nose?
red = "\e[31;10m"; . . . redb = "\e[31;7m"; redc = "\e[31;9m";

#include <stdio.h>
#define LINE 11
#define COLN 11
// String to display Rocket
const char rocket[LINE][COLN] ={
"     ^     ",
"    /^\\    ",
"    |-|    ",
"    | |    ",
"    |W|    ",
"    |E|    ",
"    |E|    ",
"    |E|    ",
"   /| |\\   ",
"  / | | \\  ",
" |  | |  | "
};
int main(){
    for(int i = 0; i< LINE; i  ){
        printf("%.*s\n",COLN, rocket[i]);
    }
    printf("\33[0;36mBut if I want to color specific parts like the description, WEEE. \33[0m");
printf("\33[31;10mIn the rocket, what will it be like?\33[0m\n");
}

CodePudding user response:

Since the escapes sequences takes some bytes in memory, it is not practical to use a fixed size array, especially a fixed number of column.

With pointers it may do the job:

#include <stdio.h>
#define LINE 11
// String to display Rocket
const char *rocket[LINE] ={
"     ^     ",
"    /^\\    ",
"    |-|    ",
"    | |    ",
"    |\33[31;10mW\33[0m|    ",
"    |\33[31;10mE\33[0m|    ",
"    |\33[31;10mE\33[0m|    ",
"    |\33[31;10mE\33[0m|    ",
"   /| |\\   ",
"  / | | \\  ",
" |  | |  | "
};
int main(){
    for(int i = 0; i< LINE; i  ){
        printf("%s\n", rocket[i]);
    }
    printf("\33[0;36mBut if I want to color specific parts like the description, WEEE. \33[0m");
printf("\33[31;10mIn the rocket, what will it be like?\33[0m\n");
}

Also some art won't be possible, since a character is basically a rectangle with 2 colors, foreground and background, it'll will not be possible to color in red the backgound only inside the nose of the rocket ; some red will spread outside.

CodePudding user response:

One of the way is identify the location then set the color above it and later reset it back. The below is not the exact solution, you can work around to figure out location of array and modify the loops.

#include <stdio.h>
#define LINE 11
#define COLN 11
// String to display Rocket
const char rocket[LINE][COLN] ={
"     ^     ",
"    /^\\    ",
"    |-|    ",
"    | |    ",
"    |W|    ",
"    |E|    ",
"    |E|    ",
"    |E|    ",
"   /| |\\   ",
"  / | | \\  ",
" |  | |  | "
};

int main(){ 
    for(int i = 0; i< 4; i  ){
        printf("%.*s\n",COLN, rocket[i]);
    }
    printf("\033[0;31m\n"); //Set the text to the color red

    for(int i = 4; i< 8; i  ){
        printf("%.*s\n",COLN, rocket[i]);
    }

    printf("\033[0m\n"); //Resets the text to default color

    for(int i = 8; i< LINE; i  ){
        printf("%.*s\n",COLN, rocket[i]);
    }
}
  • Related