Richard Jones' Log: Something I'm working on...

Wed, 19 Aug 2009

This will probably be the last of these posts before I make the project public. It has two code parts. The first is model:

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+2))
                for j in range(max(0, cell.j-1), min(self.size, cell.j+2)))
board = Board(20)

And the second is the withgui code:

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, y=cell.j*16+8, 

Resulting in (youtube vid, sorry about the quality I'm new to this):

Comment by Michael Foord on Wed, 19 Aug 2009

I thought Kitten was the new thing?? So that was pre-existing and is just an optional backend for the withgui then...

Comment by Richard Jones on Wed, 19 Aug 2009

kytten is a potential backend. Tkinter is the "reference" implementation at the moment but I'd like to have a pyglet-based backend too which implies a widget set and kytten is the most complete of the current lot.

Comment by j_king on Wed, 19 Aug 2009

I'm excited to see this released!

Great work so far. Can't wait to tinker with it.