# Cave spawning

This page explains the game's process behind spawning enemies in a cave. This is obtained through observation, and is subject to have some parts incorrect.

Editor's note: Until further notice, this only applies to spawning enemies.

## Process

Some time after the cave is built out of its available units, the game will run this "main algorithm" in order to spawn objects.

### Main algorithm

1. For each `TekiInfo` entry in the sublevel's configuration, in order...
1. Run the spawn algorithm using this entry's class, minimum spawn amount, and spawn coordinate type.
2. If the number of enemies hasn't reached `{f002}` yet...
1. For each `TekiInfo` entry in the sublevel's configuration...
1. Grab its random distribution weight and add it to a list.
2. While the number of enemies hasn't reached `{f002}`...
1. Randomly decide what enemy to spawn next, using the weighted list built in the previous step.
2. Store the enemy's type.
3. Store the spawn coordinate type.
4. Run the spawn algorithm using this entry's class, amount of 1, and this entry's spawn coordinate type.
3. Remove every spawned object that is not meant to be there (collected treasures, Candypop Buds that disappear when you have 20+, etc.)

### Spawn algorithm

This algorithm takes as parameters an object class, a spawn amount, and a spawn coordinate type.

1. While the intended amount of enemies hasn't been spawned yet...
1. Pick a valid spawn coordinate randomly.
2. If there is no valid spawn coordinate remaining, leave this algorithm.
3. Mark this spawn coordinate as used.
4. Decide how many objects to spawn here, picking randomly between the spawn coordinate's amount limits.
5. For each one in that amount...
1. If the number of objects spawned here surpasses the intended amount, leave this algorithm.
2. Spawn that object in these coordinates (randomly translated inside the circle decided by the spawn coordinate's radius).

### Coordinate check

A spawn coordinate is valid if all of the following are true:

1. It is not in a dead end cave unit.
2. It is of the intended spawn coordinate type (Enemy Group A, Plant, etc.)
3. It is in-bounds.
4. It has not been used already.
5. It is far enough away from the ship's pod (300 units for Enemy Group A, B, and C).
6. It is far enough away from the hole (200 units for Enemy Group A, 150 units for Enemy Group C, not applicable for Enemy Group B).
7. It is far enough away from the geyser (200 units for Enemy Group A, 150 units for Enemy Group C, not applicable for Enemy Group B).