summaryrefslogtreecommitdiff
path: root/Week1-Pacman/src/map.c
blob: 9f426cbece27caa954f10cd72f4a9d48cf54a4ce (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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <stdio.h>
#include <errno.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include "map.h"
#include "import_resources.h"

#define TILE_SIDE 8

void add_map_row(const char* string, struct map* map);

void load_map(const char* filename, struct map* map) {
  if(map->contents != NULL || map->colliders != NULL) {
    printf("Reallocating non empty map, exitting!\n");
    exit(1);
  }

  map->collider_count = 0;
  map->width = 0;
  map->height = 0;

  FILE* file = fopen(filename, "r");

  if(file == NULL) {
    const char* error;

    switch(errno) {
    default:
      error = "Unknown Error";
    }

    printf("Failed to load map %s, error: %s, exitting!\n",filename, error);
    exit(1);
  }

  map->height = 0;
  char buffer[1024];

  fgets(buffer, 1024, file);
  buffer[1023] = '\0';

  map->width = 1;
  for (unsigned long i = 0; i < strlen(buffer); i++) {
    if (buffer[i] == ',')
      map->width++;
  }
  fseek(file, 0, SEEK_SET);

  while(fgets(buffer, 1024, file)) {
    //Add another row to the map
    map->height++;
    map->contents =
      realloc(map->contents, map->width * map->height * sizeof(int));

    add_map_row(buffer, map);
  }

  fclose(file);
}

void add_map_row(const char* line, struct map* map) {
  int* row = &map->contents[map->width * (map->height - 1)];
  int width = map->width;

  for(int i = 0; i < width; i++) {
    sscanf(line, "%d", &row[i]);

    int length = 1;
    int j = row[i];

    //If the current tile isn't empty add a collider here
    if(row[i] != -1) {
      map->colliders =
        realloc(map->colliders, ++map->collider_count * sizeof(SDL_Rect));

      map->colliders[map->collider_count - 1] =
        (SDL_Rect) {
        .x = i * 26,
        .y = (map->height - 1) * 20,
        .w = 26,
        .h = 20
      };
    }

    if(j < 0) {
      length++;
      j = -j;
    }
    for(; j > 0; j /= 10, length++);

    line += length;
  }
}

void draw_map(struct demo* demo, struct map* map) {

  for(int i = 0; i < map->height; i++)
    for(int j = 0; j < map->width; j++) {
      int tile =
        map->contents[i * map->width + j];

      if(tile == -1) {
        continue;
      }

      SDL_Rect s = {
        .x = (tile % 36) * TILE_SIDE,
        .y = (tile / 36) * TILE_SIDE,
        .w = TILE_SIDE,
        .h = TILE_SIDE
      };

      SDL_Rect d = {
        .x = j * 26,
        .y = i * 20,
        .w = 26,
        .h = 20
      };

      demo_rendercopy(demo, map_texture, &s, &d);
    }
}