2
2
from itertools import product
3
3
4
4
class Grid :
5
- '''2D grid of values
5
+ '''2D grid of values with m columns and n rows.
6
+ >>> Grid(2, 2)
7
+ 0 0
8
+ 0 0
9
+ >>> Grid(2, 2, 1)
10
+ 1 1
11
+ 1 1
12
+ >>> Grid(3, 2)
13
+ 0 0 0
14
+ 0 0 0
15
+ >>> Grid(2, 3)
16
+ 0 0
17
+ 0 0
18
+ 0 0
19
+ >>> Grid(2,0)
20
+ Traceback (most recent call last):
21
+ ...
22
+ ValueError: Grid size cannot be smaller than 1
23
+ >>> Grid(1,-1)
24
+ Traceback (most recent call last):
25
+ ...
26
+ ValueError: Grid size cannot be smaller than 1
27
+ >>> g = Grid(3, 4)
28
+ >>> g.num_rows
29
+ 4
30
+ >>> g.num_columns
31
+ 3
6
32
'''
7
33
def __init__ (self , m , n , initial = 0 ):
34
+ if m <= 0 or n <= 0 :
35
+ raise ValueError ('Grid size cannot be smaller than 1' )
8
36
self .grid = [[initial for r in range (n )] for c in range (m )]
9
37
self .num_columns = m
10
38
self .num_rows = n
11
39
12
40
def __call__ (self , x , y ):
13
- '''Returns value at grid point (x, y)
41
+ '''Returns value at grid point (x, y).
42
+ >>> g = Grid(4, 2)
43
+ >>> g(0, 0)
44
+ 0
45
+ >>> g.set(1,1,1)
46
+ >>> g.set(3,0,2)
47
+ >>> g.set(0,1,3)
48
+ >>> g(1,1)
49
+ 1
50
+ >>> g(3,0)
51
+ 2
52
+ >>> g(0,1)
53
+ 3
54
+ >>> g(0,0)
55
+ 0
56
+ >>> g(4,0)
57
+ Traceback (most recent call last):
58
+ ...
59
+ IndexError: list index out of range
60
+ >>> g(0,4)
61
+ Traceback (most recent call last):
62
+ ...
63
+ IndexError: list index out of range
64
+ >>> g(0,-1)
65
+ 3
14
66
'''
15
67
return self .grid [x ][y ]
16
68
17
69
def set (self , x , y , value ):
18
70
'''Overrides the value at grid point (x, y)
71
+ >>> g = Grid(3, 2)
72
+ >>> g(0,0)
73
+ 0
74
+ >>> g.set(0, 0, 4)
75
+ >>> g.set(1, 0, 5)
76
+ >>> g.set(0, 1, 6)
77
+ >>> g
78
+ 4 5 0
79
+ 6 0 0
19
80
'''
20
81
self .grid [x ][y ] = value
21
82
@@ -33,9 +94,25 @@ def __str__(self):
33
94
s = ''
34
95
for y in range (self .num_rows ):
35
96
for x in range (self .num_columns ):
36
- s += str (self (x ,y ))
37
- s += '\n '
38
- return s
97
+ s += str (self (x ,y )) + ' '
98
+ s = s [:- 1 ] + '\n ' #remove last space and add newline
99
+ return s [:- 1 ] #remove last newline
100
+
101
+ def __repr__ (self ):
102
+ return str (self )
103
+
104
+ @classmethod
105
+ def _test_grid (cls ):
106
+ '''
107
+ >>> Grid._test_grid()
108
+ 0 3 6 9
109
+ 1 4 7 10
110
+ 2 5 8 11
111
+ '''
112
+ g = Grid (4 ,3 )
113
+ for i , (x , y ) in enumerate (product (range (4 ), range (3 ))):
114
+ g .set (x ,y ,i )
115
+ return g
39
116
40
117
class Flags :
41
118
Unknown = 0
@@ -142,12 +219,12 @@ def print_field(mines, flags):
142
219
print s
143
220
144
221
if __name__ == '__main__' :
222
+ import doctest
223
+ doctest .testmod ()
145
224
m ,n = 5 ,5
146
225
mines = generate_minefield (m , n , 2 )
147
226
flags = Grid (m , n , Flags .Unknown )
148
227
149
- #print(str(mines).replace('-1', '*'))
150
-
151
228
while (True ):
152
229
print_field (mines , flags )
153
230
print "Select (Column, Row): " ,
0 commit comments