Home > OS >  How do I randomly generate an element across a 5x10 grid of arrays in Python?
How do I randomly generate an element across a 5x10 grid of arrays in Python?

Time:01-11

So I'm working on a simple text-based game similar to pacman, where the letter 'c' serves as the character that the player controls using user-inputs. Across the 5x10 grid, 10 'coins' which are represented by 'o' should be randomly generated across the board. The grid, on the other hand, is composed of the symbol '-'.

The player icon, along with the coins should be randomly generated.

I've coded out a simple solution for a single line where I randomly pop an element out of a list and take that same index and insert a coin. Here's the code:

array=['-','-','-','-','-','-','-','-','-','-',]
separator = ' '

def pop():
    pos = random.randint(0,9)
    return pos

array.pop(pop())
array.insert(pop(), 'o')
print (separator.join(array))

Now I just need to make it into a 5x10 grid. Problem is, I don't know how to randomly insert 11 elements (10 coins and the player icon) across 5 rows of arrays. Help!

CodePudding user response:

instead of using your custom pop() function twice:

array.pop(pop()) 
array.insert(pop(), 'o')

you can use:

index = pop()
array.pop(index)
array.insert(index, 'o')

or a better solution would be:

index = pop()
array[index] = 'o'

CodePudding user response:

So, first we'll generate a 2d array from a list of lists using a width of 5 and a height of 10:

import random

w, h = 5, 10
two_d_array = [['-' for x in range(w)] for y in range(h)]

Next, because you want to place these items randomly without choosing the same location twice, we want to generate a random sample that doesn't have repeat values:

samples = random.sample(range(w * h), 10)

Then, for each of these sample values, we'll take the integer value of the sample value divided by the width, and we'll get the column value by getting the remainder of the sample divided by the width. And replace with the value you want.

for s in samples:
    row = int(s/w)
    column = s % w
    two_d_array[row][column] = 'o'
  •  Tags:  
  • Related