#include #include #include "level.h" void init_level(Game *g, Level *l, char *filepath) { char *file_text = LoadFileText(filepath); l->data = malloc(strlen(file_text)); char *line = NULL, *other_guy = NULL; char *first_line = strtok_r(file_text, "\n", &line); char* datum = strtok_r(first_line, ",", &other_guy); l->data_size = 0; do { l->data[l->data_size++] = atoi(datum); } while ((datum = strtok_r(NULL, ",", &other_guy))); l->width = l->data_size; while ((first_line = strtok_r(NULL, "\n", &line))) { datum = strtok_r(first_line, ",", &other_guy); do { l->data[l->data_size++] = (char)atoi(datum); } while ((datum = strtok_r(NULL, ",", &other_guy))); } l->length = l->data_size / l->width; printf( "Loaded level from '%s': %dx%d = %zd total bytes\n", filepath, l->length, l->width, l->data_size); UnloadFileText(file_text); l->game = g; } size_t level_tile_index_from_position(Level *l, Vector2 p) { size_t x_tile = p.x / 32; size_t y_tile = p.y / 32; return ((y_tile * l->width) + x_tile) % l->data_size; } FourIndices rect_corners(Level *l, Rectangle r) { return (FourIndices) { level_tile_index_from_position(l, (Vector2) { r.x, r.y }), level_tile_index_from_position(l, (Vector2) { r.x + r.width, r.y }), level_tile_index_from_position(l, (Vector2) { r.x, r.y + r.height }), level_tile_index_from_position(l, (Vector2) { r.x + r.width, r.y + r.height}), }; } Color COLORS[4] = {BLACK, DARKGRAY, GRAY, LIGHTGRAY}; void draw_tile(Level *l, float x, float y) { size_t index = (size_t)(x + (y * l->width)) % l->data_size; size_t data = l->data[index]; Color c = COLORS[data]; FourIndices fi = rect_corners(l, l->game->player->bbox); if (fi.index[0] == index) c = RED; if (fi.index[1] == index) c = RED; if (fi.index[2] == index) c = RED; if (fi.index[3] == index) c = RED; DrawRectangle(x * 32, y * 32, 32, 32, c); } void draw_level(Level *l) { float y = l->game->player->position.y; y /= 32; for (int i = 0; i < l->width; i++) { for (int j = y - 15; j < y + 15; j++) { draw_tile(l, i, j); } } }