Question:Programming a game grid ...

alex23 wuwei23 at
Thu Jun 28 02:31:34 CEST 2012

On Jun 28, 8:21 am, iconoclast011 <iconoclast... at> wrote:
> Fairly new to Python ... Is there a way to efficiently (different from my brute
> force code shown below) to set up a game grid of buttons (ie with pygame)
> responding to mouse clicks ?   I would want to vary the size of the grid ...

It hasn't been updated for a few years, but I was always impressed by
Richard Jones' use of context managers in his withgui, especially his
minesweeper example:

    import random

    class Cell(object):
        def __init__(self, i, j, has_bomb):
            self.i, self.j = i, j
            self.has_bomb = has_bomb
    class Board(list):
        def __init__(self, size, chance=.2):
            self.size = size
            self[:] = [[Cell(i, j, random.random() < chance)
                for i in range(size)] for j in range(size)]
        def count(self, cell):
            '''Count the number of bombs near the cell.'''
            return sum(self[j][i].has_bomb
                for i in range(max(0, cell.i-1), min(self.size, cell.i
                    for j in range(max(0, cell.j-1), min(self.size,

    board = Board(20)

    with gui.canvas(width=320, height=320) as canvas:
        for column in board:
            for cell in column:
                @canvas.image('cover.png', x=cell.i*16, y=cell.j*16)
                def on_mouse(image, mouse, cell=cell):
                    count = board.count(cell)
                    if cell.has_bomb:
                        image.value = 'bomb.png'
                        print 'GAME OVER!'
                    elif count:
                        canvas.label(str(count), x=cell.i*16+8,

More information about the Python-list mailing list