I'm trying to use a randomly constructed two dimensional array as a map for a text based game I'm building. If I define the world space as such:
# Map information:
self.inner = ['g'] * 60 # Creates 60 'grass' tiles.
self.outer = [.extend(self.inner) for x in self.inner]
# 'inner' & 'outer' variables define the world space as a 60 x 60 2-D array.
self.userpos = self.outer # Tracks player tile in world space.
# The variables below are modifiers for the world space.
self.town = 't'
self.enemy = 'e'
You could use
randrange to generate row and column index and add enemies there. If there's already a enemy or some other object in given cell just skip it and randomize a new coordinate:
import random def add(grid, char, count): while count: row = random.randrange(len(grid)) column = random.randrange(len(grid)) if world[row][column] == 'g': world[row][column] = char count -= 1
world = [['g'] * 60 for _ in xrange(60)] add(world, 'e', 25) add(world, 't', 5)
This approach makes only sense if your world is sparse, i.e. most of the world is grass. If world is going to be filled with different objects then tracking the free space and randomly selecting a tile from there would be better approach.