1
2
3 import unittest
4
5 class MineSweeper:
6 search_direction = {
7 'up':(-1,0),
8 'down':(1,0),
9 'left':(0,-1),
10 'right':(0,1),
11 'upleft':(-1,-1),
12 'upright':(-1,1),
13 'downleft':(1,-1),
14 'downright':(1,1)
15 }
16
17 def __init__(self, data):
18 self.info = self.parseData(data)
19
20 def parseData(self, data):
21 result = []
22 for row, line in enumerate(data.split('\n')):
23 result.append([])
24 for col, mine in enumerate(line):
25 result[row].append(mine=='*')
26 return result
27
28 def search(self, row, col, direction):
29 try:
30 if row+direction[0] < 0 or col+direction[1] < 0: raise IndexError
31 return self.info[row+direction[0]][col+direction[1]]
32 except IndexError:
33 return False
34
35 def get(self, row, col):
36 if self.info[row][col]: return '*'
37 return reduce(lambda x,y:x+y, [self.search(row, col, direction) \
38 for name, direction in self.search_direction.items()])
39
40 def __str__(self):
41 result = []
42 for row in range(len(self.info)):
43 for col in range(len(self.info[row])):
44 result.append(str(self.get(row, col)))
45 result.append('\n')
46 return ''.join(result[:-1])
47
48
49 class TestMine(unittest.TestCase):
50 def testMineSweeper(self):
51 data = '''*.*.
52 ...*
53 .*..
54 ....'''
55 ms = MineSweeper(data)
56 self.assertEquals('*', ms.get(0,0))
57 self.assertEquals(2, ms.get(0,1))
58 self.assertEquals(3, ms.get(1,2))
59
60 def testMineSweeper(self):
61 data = '''*....
62 .....
63 .*...
64 ....*'''
65 ms = MineSweeper(data)
66 self.assertEquals('*', ms.get(0,0))
67 self.assertEquals(2, ms.get(1,1))
68 self.assertEquals(0, ms.get(0,4))
69
70 def testRun(self):
71 data = '''*....
72 .....
73 .*...
74 ....*'''
75
76 expected = '''*1000
77 22100
78 1*111
79 1111*'''
80 self.assertEquals(expected, str(MineSweeper(data)))
81
82
83 if __name__ == '__main__':
84 unittest.main()