summaryrefslogtreecommitdiff
path: root/src/main.c
blob: 726e781291b51b3a1719fbc48adde65a4a034dfc (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
#include <stdbool.h>
#include <SDL3/SDL.h>
#include <time.h>
#include <stdlib.h>
#define SDL_MAIN_USE_CALLBACKS
#include <SDL3/SDL_main.h>

#include "app.h"

#define WINDOW_WIDTH 800
#define WINDOW_HEIGHT 600
#define WINDOW_TITLE "Match 3"
#define MAX_DELTATIME (1000.0 / 30)

SDL_Window* window;
SDL_Renderer* renderer;

application_state app_state;

SDL_AppResult SDL_AppInit(void**, int, char**) {
  SDL_Init(SDL_INIT_VIDEO);
  srand(time(NULL));

  window = SDL_CreateWindow(WINDOW_TITLE, WINDOW_WIDTH, WINDOW_HEIGHT, 0);
  renderer = SDL_CreateRenderer(window, NULL);
#ifndef SDL_PLATFORM_EMSCRIPTEN
  SDL_SetRenderVSync(renderer, true);
#endif

  init_app(renderer);

  return SDL_APP_CONTINUE;
}

SDL_AppResult SDL_AppEvent(void*, SDL_Event* e) {
  if (e->type == SDL_EVENT_QUIT) {
    return SDL_APP_SUCCESS;
  }

  switch (app_state) {
  case game_state:
    game_event(e);
    break;

  default:
    break;
  }

  return SDL_APP_CONTINUE;
}

SDL_AppResult SDL_AppIterate(void*) {
  static uint64_t then = 0, now = 0;

  then = now;
  now = SDL_GetTicks();

  float dt = (now - then) / 1000.0f;

  switch (app_state) {

  case game_state:
    update_game(SDL_min(dt, MAX_DELTATIME));
    draw_game(renderer);
    break;

  default:
    break;

  }

  return SDL_APP_CONTINUE;
}

void SDL_AppQuit(void*, SDL_AppResult) {
  SDL_DestroyWindow(window);
  SDL_DestroyRenderer(renderer);

  free_app();

  SDL_Quit();
}

void init_app(SDL_Renderer* renderer) {
  init_game(renderer);

  app_state = game_state;
}

void free_app() {
  free_game();
}