1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
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)
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()
|