view snake.py @ 41:bcad0f5464bf
snake.Rule.load: give reasonable error rather than crash on empty lines
author |
Daniil Alexeyevsky <me.dendik@gmail.com> |
date |
Sun, 19 Dec 2010 22:49:53 +0300 |
parents |
94945f11c78d |
children |
2a7b76d66e78 |
line source
5 line = line[:line.index('//')]
10 def __init__ (self, cells, color):
15 def load (self, file):
16 magic, name = preprocess(file.readline()).split(' ', 1)
17 assert magic == "snake", "This is not snake file"
19 line = preprocess(file.readline())
22 assert line == '', "Rules must be separated by empty lines"
23 self.rules.append(Rule().load(file))
26 for cell in self.cells:
28 snake.cells[0].type = 'head'
29 snake.cells[1:-1].type = 'body'
30 snake.cells[-1].type = 'tail'
44 def __init__ (self, snake):
46 self.direction = (1, 0)
49 def load (self, file):
52 line = preprocess(line)
53 if y == 0 and line == '':
57 assert len(line) == 8, "Rule lines must be exactly 7 chars long"
58 assert line[-1] == ';', "Rule lines must end with semicolon"
59 for x, char in enumerate(line[:8]):
60 self.parse_cell(x, y, char)
63 def parse_cell(self, x, y, char):
64 assert char.lower() in self.codes, "Illegal symbol in rule: %s" % char
65 cell = engine.Cell(x, y, None)
72 assert (x, y) == (3, 3), "Own head must in the center of rule"
74 assert char == 'h', "In the center of rule must be own head"
75 cell.type = self.codes[char.lower()]
76 self.pattern[x, y] = cell
78 def applies (self, field, x, y):
79 for px, fx in zip(range(7), range(x - 3, x + 4)):
80 for py, fy in zip(range(7), range(y - 3, y + 4)):
81 pcell = self.pattern[px, py]
82 fcell = field.get(fx, fy)
83 if pcell.type == 'any':
85 if pcell.type != fcell.type:
87 if pcell.snake == 'my' and fcell.snake != self.snake:
89 elif pcell.snake == 'enemy' and fcell.snake == self.snake:
93 def rotate (self, rot):
94 for i in range(((rot % 4) + 4) % 4):
101 pattern[y, 6 - x] = self.pattern[x, y]
102 self.pattern = pattern
103 x, y = self.direction
104 self.direction = y, -x
106 # vim: set ts=4 sts=4 sw=4 et: