I've used the following approach to generate apples on a snake clone. It's very simple, although it has some potential problems depending on your game requirements. But if you know will always be a lot more free locations that occupied locations, it should be enough in practice.
Generate a random location for the X and Y axis separately based on the size of the map, but wrap it in a do...while
loop that automatically retries whenever the location is already occupied. Something like:
// Find valid location
int x, y;
do {
x = random(0, width);
y = random(0, height);
} while(IsLocationOccupied(x, y))
// Create object there
SpawnObjectAt(x, y);
The implementation of IsLocationOccupied
depends on your game. For instance, for a tile-based game you could simply check the contents of the tile at that location. For example:
bool IsLocationOccupied(int x, int y)
{
return map[x, y] != TileType.Empty;
}
For a non-tile based game, you could iterate over all your objects and check if any of them would intersect with a new object spawning at that location. For example:
bool IsLocationOccupied(int x, int y)
{
Rectangle newBounds = new Rectangle(x, y, objectWidth, objectHeight);
foreach(Entity entity in entities)
if(entity.bounds.Intersects(newBounds))
return true;
return false;
}
A safer alternative is to somehow keep a list of all the free locations in the screen, and remove one element at random from the list when you need to spawn a new object. This is great in a tile-based game, but even in a continuous environment you can still divide it into an imaginary grid to limit the number of locations.