Re: Question:Programming a game grid ...

Discussion in 'Python' started by alex23, Jun 28, 2012.

  1. alex23

    alex23 Guest

    On Jun 28, 8:21 am, iconoclast011 <> wrote:
    > Fairly new to Python ... Is there a way to efficiently (different from mybrute
    > 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].has_bomb
    for i in range(max(0, cell.i-1), min(self.size, cell.i
    +2))
    for j in range(max(0, cell.j-1), min(self.size,
    cell.j+2)))

    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:
    image.destroy()
    canvas.label(str(count), x=cell.i*16+8,
    y=cell.j*16+8,
    anchor=center)
    else:
    image.destroy()

    http://www.mechanicalcat.net/richard/log/Python/Something_I_m_working_on.7
    https://code.launchpad.net/withgui
    alex23, Jun 28, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. BlackHawke
    Replies:
    12
    Views:
    1,569
    Andrew Thompson
    Jan 26, 2004
  2. Max Kubierschky
    Replies:
    10
    Views:
    1,845
    pabloreda
    Mar 31, 2007
  3. David
    Replies:
    7
    Views:
    235
    Steven D'Aprano
    Jun 28, 2012
  4. MRAB
    Replies:
    0
    Views:
    178
  5. Rick Johnson

    Re: Question:Programming a game grid ...

    Rick Johnson, Jun 28, 2012, in forum: Python
    Replies:
    0
    Views:
    207
    Rick Johnson
    Jun 28, 2012
Loading...

Share This Page