Search code examples
pythonwxwidgets

How can I set a cell in python matrix?


that's my problem:

self.gameField = [
    ['-', '-', '-', '-', '-', '-', '-']
    ['-', '-', '-', '-', '-', '-', '-']
    ['-', '-', '-', '-', '-', '-', '-']
    ['-', '-', '-', '-', '-', '-', '-']
    ['-', '-', '-', '-', '-', '-', '-']
    ['-', '-', '-', '-', '-', '-', '-']
]

As you can see, I've created a matrix using list, I need to change a single element of a column selected by user, so I've tried with this code:

for z in self.gameField:
    if z[num] == "-":
        z[num] = "X"
        print "Done"

Where 'num' is an integer from 0 to 6 to indicate the sub-list. I want to select a colum, and set the lowest ' - ' available (like if there's gravity), so for example, if I select '0'

        ['-', '-', '-', '-', '-', '-', '-']
        ['-', '-', '-', '-', '-', '-', '-']
        ['-', '-', '-', '-', '-', '-', '-']
        ['-', '-', '-', '-', '-', '-', '-']
        ['-', '-', '-', '-', '-', '-', '-']
        ['X', '-', '-', '-', '-', '-', '-']

But actually my program change the value of all the column

        ['X', '-', '-', '-', '-', '-', '-']
        ['X', '-', '-', '-', '-', '-', '-']
        ['X', '-', '-', '-', '-', '-', '-']
        ['X', '-', '-', '-', '-', '-', '-']
        ['X', '-', '-', '-', '-', '-', '-']
        ['X', '-', '-', '-', '-', '-', '-']

How can I fix it? Have you got any ideas to do that?


Solution

  • Putting previous comments together:

    Assuming your grid is created well (see possible issue with multiple sub-lists references - basically if you created your grid with something like self.gameField = [[['_']*7]*6], which seems short and clean, it is actually bad in your case), you just need to break out of the for loop as soon as you place an "X" (otherwise you just keep filling the whole column!):

    for z in self.gameField:
        if z[num] == "-":
            z[num] = "X"
            print "Done"
            break
    

    Note that you might want to iterate your rows (your for loop) in reverse order so that gravity is downwards when you print your grid (or print your grid in reverse)...