roger roger - 1 year ago 69
Python Question

How can I use x, y coordinate matrices to choose where a character appears in a string with python?

I am attempting to make a simple maze game to test a NNS with genetic algorithms.
the maze for each test would use a matrix to hold the x, y points of things like barriers, the start, the end, and the player's current position. The main thing that I need help with is placing the right character in the right location in a string so when the strings of row 1-25 are read (probably with a for loop) it will read out a layout of the map. As an example, the barrier points 1,1 3,4 and 1,5 would look like this if an "o" is a space:
first string

second string
third string
fourth string
Any ideas? Thanks in advance!

Answer Source

You're probably looking for something along the lines of this:

width = 6
height = 6
coords = [(1,1),(3,4),(1,5)]
print('\n'.join(['|' + ''.join(['x' if (x,y) in coords else 'o' for x in range(width)]) + '|' for y in range(height)]))

Using list comprehension, we can easily construct each row one at a time:

''.join(['x' if (x,y) in coords else 'o' for x in range(width)])

Basically, print an x if the coordinate contains something, otherwise use o.

Add the side bars in...

'|' + ''.join([...]) + '|'

''.join() is a very useful function for this.

Then all we have to do is repeat this for each row, making sure to insert a line break between each row.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download