PyDive PyDive - 5 months ago 21
Python Question

How to change the values of multiple indexes?

worldArray = [["." for i in range(5)] for i in range(5)]


This produces a map that I can use for my game. It should look something like:

[['.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.']]


Let's say the
'.'
represents a grass tile. If I wanted to replace a specific number of indexes to
'~'
instead to represent a water tile, what would be the easiest way of doing so? I want the map to look a bit like:

[['.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.'],
['~', '~', '.', '.', '.'],
['~', '~', '~', '.', '.']]


I know I can manually go through and change each specific index to show the
'~'
tile, but the real in-game map I use is 40 x 40 instead -- which would make the job of individually replacing each index a bit tedious and redundant. I would like to be able to define which tiles I want replaced, i.e. row 4, columns 1 - 2; row 5, columns 1 - 3. how could I go about doing that?

Answer

You could write a helper function

def replace_at_position(world_array, row_col_dict, repl_char):
    """
    Use row_col_dict in format of {row : (startOfRange, endOfRange)} to replace the characters
    inside the specific range at the specific row with repl_char
    """

    for row in row_col_dict.keys():
        startPos, endPos = row_col_dict[row]

        for i in range(startPos, endPos):
            worldArray[row][i] = repl_char
    return worldArray

You can use it like this:

worldArray = [["." for i in range(10)] for j in range(5)]

# replace row 2 (the third row) colums 0-4 (inclusive, exclusive, like range) with character '~'
worldArray = replace_at_position(worldArray, {2 : (0,10)}, '~')

#replace row 1 (the second row) colums 0-5 (inc, exc, like range) with character '~'
worldArray = replace_at_position(worldArray, {1 : (0, 5)}, '~')

pprint.pprint(worldArray)

This will result in:

[['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],
 ['~', '~', '~', '~', '~', '.', '.', '.', '.', '.'],
 ['~', '~', '~', '~', '~', '~', '~', '~', '~', '~'],
 ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],
 ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.']]
Comments