[Tutor] Help with excetion handing and making my code more efficient needed please

Matt Smith matt at mattanddawn.orangehome.co.uk
Fri May 18 23:37:07 CEST 2007


I am trying to write a simple program to display Conway's Game Of Life.
I have the bones of the program together but I'm struggling with the
function that tests for and applies the rules of the game (the important
bit). I have the current state of the game stored in a 2d matrix with
each cell represented by a 1 or 0 (alive or dead) i.e: [[0, 1, 0], [1,
0, 0], [0, 0, 0]]. I'm using a 15 * 15 matrix for testing purposes. I
have come up with the following function to update the matrix so far:

def update_matrix(matrix):
    matrix_updated = [matrix]
    # Perform check for each value in the matrix
    for x in range(len(matrix[0])):
        for y in range(len(matrix)):
            neighbour_count = 0
            if matrix[x-1][y+1]: neighbour_count = neighbour_count + 1 
            if matrix[x][y+1]: neighbour_count = neighbour_count + 1
            if matrix[x+1][y+1]: neighbour_count = neighbour_count + 1
            if matrix[x+1][y]: neighbour_count = neighbour_count + 1
            if matrix[x+1][y-1]: neighbour_count = neighbour_count + 1
            if matrix[x][y-1]: neighbour_count = neighbour_count + 1
            if matrix[x-1][y-1]: neighbour_count = neighbour_count + 1
            if matrix[x-1][y]: neighbour_count = neighbour_count + 1
            # Apply game of life rules to each item in the matrix
            if 2 < neighbour_count > 3:
                matrix_updated[x][y] = 0
            elif neighbour_count == 3:
                matrix_updated[x][y] = 1
            # No need to change values if neighbour count == 2
    return matrix_updated

I have two problems with this code: Firstly, when testing cells on the
edges of the matrix, I get an IndexError because I am testing an item in
the list that does not exist. I want the program to assume that cells
outside the bounds of the board are automatically dead. I am not sure
how to suppress or avoid this error so that neighbour_count is not
incremented for indexes outside the matrix.

My second problem is that this function seems to be very clunky to me
(even if it did work...). I cannot think of a way of checking each of
the 8 cells surrounding the one being tested without doing it this way.
Is there a better way of doing this?

Thanks in advance, Matt.

More information about the Tutor mailing list