Search code examples
pythonpygamerectconways-game-of-life

getting pygame.Rect color without classes


I'm trying to code Conway's game of life as a part of job qualification test, using Python and ONLY PyGame library without classes my approach to this is to create a grid of rectangles and assigning each rectangle to an 2d array up to this point this approach is done, now as part of the game's rules i need to check the rectangles color, is there is a way to check a pygame.Rect object its color?

each rectangle created in this way:

for y in range(0, WindowDimensions[1], CellSize):
    for x in range(0, WindowDimensions[0], CellSize):
        cell = pygame.Rect(x, y, CellSize, CellSize)
        AddCellToArray(cell)
        pygame.draw.rect(surface=Window, color=BLACK, rect=cell, width=1)
Column, Row = 0, 0

def AddCellToArray(cell):
    nonlocal Column, Row
    if Row < len(BoardArr):
        if Column < len(BoardArr[0]):
            BoardArr[Row][Column] = cell
            Column += 1
        else:
            Row += 1
            Column = 0
            BoardArr[Row][Column] = cell
            Column += 1

Solution

  • A pygame.Rect object has no color. When you call pygame.draw.rect the area on the screen defined by the rectangle is filled with the color.

    Store the rectangle and its color in BoardArr:

    for y in range(0, WindowDimensions[1], CellSize):
        for x in range(0, WindowDimensions[0], CellSize):
            cell = pygame.Rect(x, y, CellSize, CellSize)
            color = BLACK
            AddCellToArray(cell, color)
            pygame.draw.rect(surface=Window, color=color, rect=cell, width=1)
    
    Column, Row = 0, 0
    
    def AddCellToArray(cell, color):
        nonlocal Column, Row
        if Row < len(BoardArr):
            if Column < len(BoardArr[0]):
                BoardArr[Row][Column] = [cell, color]
                Column += 1
            else:
                Row += 1
                Column = 0
                BoardArr[Row][Column] = [cell, color]
                Column += 1