From f9734c3c0ab742a3e2ebcc7c7414f5558c5b94ce Mon Sep 17 00:00:00 2001 From: odweta Date: Sat, 10 Oct 2026 14:46:08 +0200 Subject: [PATCH] add better colors for 2048 --- src/examples/2048.c | 39 ++++++++++++++++++++++++++++++++++++- src/examples/CMakeLists.txt | 1 + 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/examples/2048.c b/src/examples/2048.c index 354d9b9..8985825 100644 --- a/src/examples/2048.c +++ b/src/examples/2048.c @@ -10,6 +10,7 @@ #include #include #include +#include #define SIZE 4 #define MOVE_DURATION 0.12f @@ -74,6 +75,42 @@ colors(uint32_t number) } } +/* Maps positive values logarithmically: powers of two get evenly spaced hues. + Returns 0xRRGGBB. Values outside [min_value, max_value] are clamped. */ +uint32_t +color_for_value(double value, double min_value, double max_value) +{ + if (min_value <= 0.0 || max_value <= min_value || value <= 0.0) + return 0xFFFFFF; + + if (value < min_value) value = min_value; + if (value > max_value) value = max_value; + + double t = (log2(value) - log2(min_value)) / + (log2(max_value) - log2(min_value)); + + t = sqrt(t); /* accelerates color changes near the low end */ + + /* Sweep hue from blue to red in HSV; full saturation and brightness. */ + // double h = (1.0 - t) * 240.0; + + double exponent = log2(value / min_value); /* 0 at min_value, 1 per doubling */ + double h = fmod(20.0 + exponent * 45.0, 360.0); + + double c = 1.0; + double x = 1.0 - fabs(fmod(h / 60.0, 2.0) - 1.0); + double r, g, b; + + if (h < 60.0) { r = c; g = x; b = 0.0; } + else if (h < 120.0) { r = x; g = c; b = 0.0; } + else if (h < 180.0) { r = 0.0; g = c; b = x; } + else { r = 0.0; g = x; b = c; } + + return ((uint32_t)(r * 255.0) << 16) | + ((uint32_t)(g * 255.0) << 8) | + (uint32_t)(b * 255.0); +} + /* * Return the board coordinate for position p in a line, where p=0 is * the side toward which tiles move. @@ -323,7 +360,7 @@ draw_tile_rect(uint32_t value, float x, float y, float w, float h) uint32_t iy = (uint32_t)y; uint32_t iw = (uint32_t)w; uint32_t ih = (uint32_t)h; - uint32_t color = colors(value); + uint32_t color = color_for_value((double)value, 2, 131072); put_rect(OVERDRAW, ix, iy, iw, ih, color); diff --git a/src/examples/CMakeLists.txt b/src/examples/CMakeLists.txt index 81d3f48..64be64c 100644 --- a/src/examples/CMakeLists.txt +++ b/src/examples/CMakeLists.txt @@ -3,6 +3,7 @@ add_executable(game_2048 2048.c) target_link_libraries(game_2048 PRIVATE dangerzone_engine) +target_link_libraries(game_2048 PRIVATE m) #add_executable(game_window window.c) #target_link_libraries(game_window PRIVATE dangerzone_engine)