starship/level.c

57 lines
1.4 KiB
C

#include <string.h>
#include <stdio.h>
#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;
}
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];
DrawRectangle(x * 32, y * 32, 32, 32, c);
}
void draw_level(Level *l) {
Camera2D *camera = l->game->camera;
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);
}
}
}