PyDive PyDive - 1 year ago 42
Python Question

How to create a random multidimensional array from existing variables

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:

class WorldSpace(object):
# Map information:
def __init__(self):
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[0][0] # Tracks player tile in world space.
# The variables below are modifiers for the world space. = 't'
self.enemy = 'e'

I assume I would use a for loop to access the array data of self.outer -- using maybe the random module to determine what tiles will be replaced -- but how would I go about randomly replacing that data with specific modifier variables, and restricting how much data is being replaced? For example, if I wanted to replace about 25 of the original grass, or 'g', tiles with enemy, or 'e', tiles, how could I do that? Same with maybe 5 randomly placed towns?

Thanks for any replies.

Answer Source

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[0]))
        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.