From 61252071880c625b367623191cc86b3a98b8d562 Mon Sep 17 00:00:00 2001 From: BoredGuy Date: Mon, 23 Dec 2024 12:32:54 +0300 Subject: Work started on adding a level system - Levels load from tiled CSV export - Levels also draw We need to add collisions with the level and adjust the level's width and height to fit well in a 4:3 window --- Week1-Pacman/src/map.c | 115 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 Week1-Pacman/src/map.c (limited to 'Week1-Pacman/src/map.c') diff --git a/Week1-Pacman/src/map.c b/Week1-Pacman/src/map.c new file mode 100644 index 0000000..0610fd4 --- /dev/null +++ b/Week1-Pacman/src/map.c @@ -0,0 +1,115 @@ +#include +#include +#include +#include +#include "map.h" + +#define TILE_SIDE 8 + +SDL_Texture* map_texture = NULL; + +void add_map_row(const char* string, int* row, int width); + +void load_map(const char* filename, struct map* map) { + if(map->contents != NULL) { + printf("Reallocating non empty map, exitting!\n"); + exit(1); + } + + 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->contents[map->width * (map->height - 1)], + map->width); + } + + fclose(file); +} + +void add_map_row(const char* line, int* row, int width) { + for(int i = 0; i < width; i++) { + sscanf(line, "%d", &row[i]); + + int length = 1; + int j = row[i]; + + 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); + } +} + +void map_init(struct demo* demo) { + map_texture = + IMG_LoadTexture(demo->ren, "assets/Sprites/Tileset.png"); + + if(map_texture == NULL) { + printf("Failed to load map tileset, error: %s, exitting!\n", + SDL_GetError()); + exit(1); + } +} -- cgit v1.2.3