0

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.
        self.town = '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.

1
  • 1
    x = shuffle(range(60)); y = shuffle(range(60)) and then that gives you a list of non repeating random tiles to replace. Commented May 9, 2016 at 2:29

1 Answer 1

1

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

Usage:

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hey thanks. That seems to be working great. Appreciate the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.