summaryrefslogtreecommitdiff
path: root/src/menu.c
blob: ebf5718ffb919c855d8c342d7441d038420c7ab6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include "app.h"
#include "font.h"

#define MENU_ITEM_TOP_YPOS_RELATIVE 0.3
#define MENU_ITEM_YOFFSET_RELATIVE 0.03
#define UNSELECTED_ITEM_SCALE 1
#define SELECTED_ITEM_SCALE 1.2

typedef enum {
  timed_mode_option = 0,
  exit_option
} menu_option;

menu_option selected_option;
sprite_font text_font;

extern SDL_Window* window;
extern application_state app_state;

void init_menu(SDL_Renderer* renderer) {
  if (text_font.spritesheet == NULL) {
    load_sprite_font(renderer,
                     "assets"DIRSEP"Fonts"DIRSEP"Peaberry-Font-v2.0"DIRSEP"Peaberry Bitmap Fonts"DIRSEP"1. WhitePeaberry"DIRSEP"2. White Peaberry"DIRSEP"WhitePeaberry.txt",
                     &text_font);
  }

  selected_option = timed_mode_option;
}

void draw_menu(SDL_Renderer* renderer) {
  SDL_RenderClear(renderer);

  const char* labels[] = {
    "Timed Mode",
    "Exit",
  };

  float yp = MENU_ITEM_TOP_YPOS_RELATIVE;
  for (menu_option i = timed_mode_option; i <= exit_option; i++) {
    float scale = i == selected_option ? SELECTED_ITEM_SCALE : UNSELECTED_ITEM_SCALE;

    draw_text_with_spritefont_extended(renderer,
                                       &text_font,
                                       (unsigned char*)labels[i],
                                       get_window_relative_xpos(0.5),
                                       get_window_relative_ypos(yp),
                                       scale
                                      );
    yp += MENU_ITEM_YOFFSET_RELATIVE;
  }

  SDL_RenderPresent(renderer);
}

static inline void select_next_option() {
  selected_option = SDL_min(selected_option+1, exit_option);
}

static inline void select_previous_option() {
  if (selected_option > timed_mode_option) {
    selected_option--;
  }
}

SDL_AppResult menu_execute_action() {
  if (selected_option == exit_option) {
    return SDL_APP_SUCCESS;
  } if (selected_option == timed_mode_option) {
    init_timed_game(NULL, NULL, 40);
    app_state = game_state;
  }

  return SDL_APP_CONTINUE;
}

SDL_AppResult menu_event(SDL_Event* e) {
  if (e->type == SDL_EVENT_KEY_DOWN) {
    SDL_Scancode pressed_button = e->key.scancode;

    if (pressed_button == SDL_SCANCODE_RETURN) {
      return menu_execute_action();
    } else if (pressed_button == SDL_SCANCODE_DOWN) {
      select_next_option();
    } else if (pressed_button == SDL_SCANCODE_UP) {
      select_previous_option();
    }
  }

  return SDL_APP_CONTINUE;
}

void free_menu() {
  free_sprite_font(&text_font);
}