0

I'm currently doing a project, and in the code I have, I'm trying to get trees .*. and mountains .^. to spawn in groups around the first tree or mountain which is spawned randomly, however, I can't figure out how to get the trees and mountains to spawn in groups around a single randomly generated point. Any help?

grid = []
def draw_board():
    row = 0
    for i in range(0,625):
        if grid[i] == 1:
            print("..."),
        elif grid[i] == 2:
            print("..."),
        elif grid[i] == 3:
            print(".*."),
        elif grid[i] == 4:
            print(".^."),
        elif grid[i] == 5:
            print("[T]"),
        else:
            print("ERR"),
        row = row + 1
        if row == 25:
            print ("\n")
            row = 0 
    return
Kraegan Epsilon
  • 367
  • 1
  • 2
  • 11

1 Answers1

0

There's a number of ways you can do it.

Firstly, you can just simulate the groups directly, i.e. pick a range on the grid and fill it with a specific figure.

def generate_grid(size):
    grid = [0] * size
    right = 0
    while right < size:
        left = right
        repeat = min(random.randint(1, 5), size - right) # *
        right = left + repeat
        grid[left:right] = [random.choice(figures)] * repeat
    return grid

Note that the group size need not to be uniformly distributed, you can use any convenient distribution, e.g. Poisson.

Secondly, you can use a Markov Chain. In this case group lengths will implicitly follow a Geometric distribution. Here's the code:

def transition_matrix(A):
    """Ensures that each row of transition matrix sums to 1."""
    copy = []
    for i, row in enumerate(A):
        total = sum(row)
        copy.append([item / total for item in row])
    return copy


def generate_grid(size):
    # Transition matrix ``A`` defines the probability of 
    # changing from figure i to figure j for each pair 
    # of figures i and j. The grouping effect can be
    # obtained by setting diagonal entries A[i][i] to 
    # larger values.
    # 
    # You need to specify this manually. 
    A = transition_matrix([[5, 1], 
                           [1, 5]])  # Assuming 2 figures.

    grid = [random.choice(figures)]
    for i in range(1, size): 
        current = grid[-1]
        next = choice(figures, A[current])
        grid.append(next)
    return grid

Where the choice function is explained in this StackOverflow answer.

Community
  • 1
  • 1
Sergei Lebedev
  • 2,659
  • 20
  • 23