Try to get a good position to spawn at. Also gets a good initial move-direction based on where you spawn.

This commit is contained in:
2025-12-18 12:57:06 +01:00
parent 199afff820
commit c1f43fdc61
5 changed files with 99 additions and 11 deletions

View File

@@ -31,11 +31,15 @@ Game_World *game_world_create(uint32_t seed, uint16_t level_width, uint16_t leve
{ // TEMP: SS - Testing ..
for(uint16_t i = 0; i < 8; i++) {
Entity_ID entity_food;
uint16_t x = 0;
uint16_t y = 0;
assert(game_world_find_position_to_spawn(w, &x, &y));
assert(game_world_create_entity(
w,
Entity_Type_Food,
(uint16_t)random_u32_range(&w->random_generator, 0, level_width),
(uint16_t)random_u32_range(&w->random_generator, 0, level_height),
x, y,
&entity_food
));
}
@@ -127,4 +131,63 @@ Entity *game_world_try_get_entity_by_id(Game_World *world, Entity_ID id) {
}
return &world->entities[id];
}
bool game_world_find_position_to_spawn(Game_World *world, uint16_t *out_x, uint16_t *out_y) {
assert(world != NULL);
assert(out_x != NULL);
assert(out_y != NULL);
uint8_t attempts = MAX_ATTEMPTS_AT_FINDING_POSITION_TO_SPAWN;
while(attempts > 0) {
uint16_t potential_x = random_u32_range(&world->random_generator, 0, (uint32_t) world->grid.width);
uint16_t potential_y = random_u32_range(&world->random_generator, 0, (uint32_t) world->grid.height);
Grid_Cell *cell = grid_get_cell(&world->grid, potential_x, potential_y);
assert(cell != NULL);
// Check if cell is free.
if(cell->entity == NULL) {
*out_x = potential_x;
*out_y = potential_y;
return true;
}
if(attempts > 0) {
attempts -= 1;
}
else {
break;
}
}
*out_x = 0;
*out_y = 0;
return false;
}
Entity_Movement_Direction game_world_choose_initial_move_direction_based_on_coords(Game_World *world, uint16_t x, uint16_t y) {
assert(world != NULL);
Grid *grid = &world->grid;
// TODO: SS - Consider potential obstacles in the grid (lava, walls etc) if we ever have them.
if (x == 0) {
return Entity_Movement_Direction_Right;
}
if (x == grid->width - 1) {
return Entity_Movement_Direction_Left;
}
if (y == 0) {
return Entity_Movement_Direction_Down;
}
if (y == grid->height - 1) {
return Entity_Movement_Direction_Up;
}
return Entity_Movement_Direction_Up;
}

View File

@@ -29,4 +29,9 @@ void game_world_destroy_entity(Game_World *world, Entity_ID entity_id, bool dest
Entity *game_world_try_get_entity_by_id(Game_World *world, Entity_ID id);
#define MAX_ATTEMPTS_AT_FINDING_POSITION_TO_SPAWN 8
bool game_world_find_position_to_spawn(Game_World *world, uint16_t *out_x, uint16_t *out_y);
Entity_Movement_Direction game_world_choose_initial_move_direction_based_on_coords(Game_World *world, uint16_t x, uint16_t y);
#endif