Could this switch statement be shortened? Is it proper way of doing this? It is a simple thing and I don't know if there is a sense to use switch.
This part of code iterates through an array to take value of intesivity of color(form 0 to about 10) and draw a square with this color using allegro library. So for 7 and more it will be black, for less it will be grey and for 1 it will be very light grey.
for (int j = 0; j < 50; j++) {
for (int i = 0; i < 50; i++) {
int value = cells[i + j * 50];
if(value > 0) {
unsigned char color;
switch (value) {
case 1 :
color = 200;
break;
case 2 :
color = 180;
break;
case 3 :
color = 140;
break;
case 4 :
color = 100;
break;
case 5 :
color = 60;
break;
case 6 :
color = 40;
break;
case 7 :
color = 20;
break;
default: color = 0;
}
al_draw_filled_rectangle(i * 8, 400 - (j * 8), i * 8 + 8, 400 - (j * 8 + 8),
al_map_rgb(color, color, color));
}
}
}
You can use a lookup table instead of switch
statement
static const unsigned char COLORS[] = { 0, 200, 180, 140, 100, 60, 40, 20 };
unsigned char color =
value >= 0 && value < sizeof COLORS / sizeof *COLORS ? COLORS[value] : 0;