Search code examples
pythonmatrix

How do I replace the entries in a matrix?


row_len = 5
col_len = 5

matrix = []

#Fills the matrix with #'s
def fill_maze():
    row = []
    for i in range(row_len):
        row.append("#")
    for i in range (col_len):
        matrix.append(row)

# Draws the maze to the screen
def draw():
    for i in range(col_len):
        row = matrix[i]
        a = ("")
        for i in row:
            a += i
        print(a)

#Swaps out the character in the given coordinate with @
def dig(x, y):
    row = matrix[y]
    row[x] = "@"
    matrix[y] = row

fill_maze()
dig(2, 3)
print("")
draw()

I'm making this text maze game where the character has to traverse a maze and I have the maze stored as a matrix. Currently I'm facing trouble changing out parts of the maze using this dig(x, y) function.

I think I've pinned down the problem to this function:

def dig(x, y):
    row = matrix[y]
    row[x] = "@"
    matrix[y] = row

When I run the program I expect it to output:

#####
#####
#####
##@##
#####

But instead it outputs:

##@##
##@##
##@##
##@##
##@##

I tried removing this part of the function: matrix[y] = row

I also tried:

def dig(x, y):
    matrix[x][y] = "@"

but that gave the same output.


Solution

  • The issue isn't with how you try to update the matrix, but how you initialize it - you have the same row multiple times, so when you think you're updating one of them, you're actually updating "all" of them, because they're actually the same row variable.
    instead, you should use a different row array for each row:

    #Fills the matrix with #'s
    def fill_maze():
        for i in range (col_len):
            row = []
            for i in range(row_len):
                row.append("#")
    
            matrix.append(row)
    

    Or, in more idiomatic fashion:

    def fill_maze():
        matrix = [['#'] * col_len for _ in range(row_len)]