]> git.lizzy.rs Git - dungeon_game.git/blob - plugins/score/score.c
Fancy up score display
[dungeon_game.git] / plugins / score / score.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <math.h>
5 #include "../game/game.h"
6
7 static int score = 0;
8 static int needed_score = 5;
9 static int level = 0;
10 static char *level_symbol = NULL;
11 static size_t level_symbol_len = 0;
12 static double score_timer = 0.0;
13 static double level_timer = 0.0;
14
15 static void level_up()
16 {
17         level += 1;
18         needed_score = (level + 1) * 5;
19
20         if (level_symbol)
21                 free(level_symbol);
22
23         get_roman_numeral(level, &level_symbol, &level_symbol_len);
24
25         level_timer = 2.0;
26 }
27
28 void add_score(int s)
29 {
30         score += s;
31
32         if (score >= needed_score) {
33                 score -= needed_score;
34                 level_up();
35         } else {
36                 score_timer = 2.0;
37         }
38 }
39
40 int get_score()
41 {
42         return score;
43 }
44
45 int get_level()
46 {
47         return level;
48 }
49
50 static void render_score(struct winsize ws)
51 {
52         int bar_flash = clamp(score_timer * 255, 0, 255);
53         set_color((struct color) {bar_flash, 255, bar_flash}, true);
54
55         int level_flash = clamp(level_timer * 255, 0, 255);
56         set_color((struct color) {255, 255, 255 - level_flash}, false);
57
58         size_t level_len = level_symbol_len > 0 ? 6 + level_symbol_len + 1 : 0;
59         char level_display[level_len];
60
61         if (level_len > 0)
62                 sprintf(level_display, "Level %s", level_symbol);
63
64         int bar = (double) score / (double) needed_score * ws.ws_col;
65         int level_start = (ws.ws_col - level_len) / 2;
66         int level_end = level_start + level_len - 1;
67
68         for (int i = 0; i < ws.ws_col; i++) {
69                 if (i == bar)
70                         printf("\e[49m");
71
72                 if (i >= level_start && i < level_end)
73                         printf("%c", level_display[i - level_start]);
74                 else
75                         printf(" ");
76         }
77
78         printf("\n");
79 }
80
81 static void score_globalstep(double dtime)
82 {
83         if (level_timer > 0.0)
84                 level_timer -= dtime;
85
86         if (score_timer > 0.0)
87                 score_timer -= dtime * 3.0;
88 }
89
90 __attribute__ ((constructor)) static void init()
91 {
92         register_render_component(&render_score);
93         register_globalstep((struct globalstep) {
94                 .run_if_dead = true,
95                 .callback = &score_globalstep,
96         });
97 }