Skip to content

Instantly share code, notes, and snippets.

@MX-2000
Created March 26, 2025 10:54
Show Gist options
  • Save MX-2000/3d84dd26f463eb1607eb7d4b4c788358 to your computer and use it in GitHub Desktop.
Save MX-2000/3d84dd26f463eb1607eb7d4b4c788358 to your computer and use it in GitHub Desktop.
void spawn_foods(CCpr *env) {
// After each step, check existing foods and spawns new food in the
// neighborhood Iterates over food_list for efficiency instead of the entire
// grid.
FoodList *foods = env->foods;
int original_size = foods->size;
for (int i = 0; i < original_size; i++) {
int idx = foods->indexes[i];
int offset = idx - env->width - 1; // Food spawn in 1 radius
int r = offset / env->width;
int c = offset % env->width;
for (int ri = 0; ri < 3; ri++) {
for (int ci = 0; ci < 3; ci++) {
int grid_idx = grid_index(env, (r + ri), (c + ci));
if (env->grid[grid_idx] == EMPTY) {
switch (env->grid[idx]) {
// %Chance spawning new food
case NORMAL_FOOD:
if ((rand() / (double)RAND_MAX) < env->food_base_spawn_rate) {
add_food(env, grid_idx, env->grid[idx]);
}
break;
case INTERACTIVE_FOOD:
if ((rand() / (double)RAND_MAX) <
(env->food_base_spawn_rate / 10.0)) {
add_food(env, grid_idx, env->grid[idx]);
}
break;
}
}
}
}
}
// Each turn there is random probability for a food to spawn at a random
// location To cope with resource depletion
int normalizer = (env->width * env->height) / 576;
if ((rand() / (double)RAND_MAX) <
min((env->food_base_spawn_rate * 2 * normalizer), 1e-2)) {
spawn_food(env, NORMAL_FOOD);
}
if ((rand() / (double)RAND_MAX) <
min((env->food_base_spawn_rate / 5.0 * normalizer), 5e-3)) {
spawn_food(env, INTERACTIVE_FOOD);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment