Make buttons trigger
[erdslangetjie.git] / erdslangetjie / level.py
1 # The level object
2
3 import os
4 from data import load_image, load, filepath
5
6 WALL = '.'
7 FLOOR = ' '
8 ENTRY = 'E'
9 EXIT = 'X'
10 GATE = 'G'
11 BUTTON = 'B'
12
13
14 class Level(object):
15
16     def __init__(self, levelfile):
17         self._data = []
18         self.exit_pos = []
19         self.enter_pos = None
20         self._tiles = []
21         self._changed = []
22         self._gates = {}
23         self._buttons = {}
24         # Because of how kivy's coordinate system works,
25         # we reverse the lines so things match up between
26         # the file and the display (top of file == top of display)
27         for line in reversed(levelfile.readlines()):
28             self._data.append(list(line.strip('\n')))
29
30     def load_tiles(self):
31         """Load the list of tiles for the level"""
32         self._tiles = []
33         self._gates = {}
34         self._buttons = {}
35         self.exit_pos = []
36         self._changed = []
37         self.enter_pos = None
38         for j, line in enumerate(self._data):
39             tile_line = []
40             for i, c in enumerate(line):
41                 tile_image = self._get_tile_image((i, j), c)
42                 tile_line.append(tile_image)
43             self._tiles.append(tile_line)
44
45     def _get_tile_image(self, pos, c):
46         image = None
47         if c == FLOOR:
48             image = load_image('tiles/floor.png')
49         elif c == WALL:
50             image = self._get_wall_tile(pos)
51         elif c == ENTRY:
52             self.enter_pos = pos
53             image = load_image('tiles/entry.png')
54         elif c == EXIT:
55             self.exit_pos.append(pos)
56             image = load_image('tiles/door.png')
57         elif c == GATE:
58             if pos not in self._gates:
59                 self._gates[pos] = -1  # down
60                 image = load_image('tiles/gate_down.png')
61             else:
62                 state = self._gates[pos]
63                 if state == -1:
64                     image = load_image('tiles/gate_down.png')
65                 elif state == 0:
66                     # destroyed
67                     image = load_image('tiles/floor.png')
68                 elif state == 1:
69                     # badly damaged
70                     image = load_image('tiles/gate_dented.png')
71                 elif state == 2:
72                     # lightly damaged
73                     image = load_image('tiles/gate_bent.png')
74                 else:
75                     # gate up
76                     image = load_image('tiles/gate_up.png')
77         elif c == BUTTON:
78             if not pos in self._buttons:
79                 image = load_image('tiles/button.png')
80                 self._buttons[pos] = 'active'
81             elif self._buttons[pos] == 'active':
82                 image = load_image('tiles/button.png')
83             else:
84                 image = load_image('tiles/floor.png')
85         if image is None:
86             raise RuntimeError('Unknown tile type %s at %s' % (c, pos))
87         return image
88
89     def validate(self):
90         entry_points = 0
91         exit_points = 0
92         gates = 0
93         buttons = 0
94         for line in self._data:
95             if ENTRY in line:
96                 entry_points += line.count(ENTRY)
97             if EXIT in line:
98                 exit_points += line.count(EXIT)
99             if BUTTON in line:
100                 buttons += line.count(BUTTON)
101             if GATE in line:
102                 gates += line.count(GATE)
103         if entry_points == 0:
104             raise RuntimeError('No entry point')
105         if entry_points > 1:
106             raise RuntimeError('Multiple entry points')
107         if exit_points == 0:
108             raise RuntimeError('No exit')
109         if gates != buttons:
110             raise RuntimeError('The number of buttons and gates differ')
111
112     def get_tiles(self):
113         return self._tiles
114
115     def get_single_tile(self, pos):
116         return self._tiles[pos[1]][pos[0]]
117
118     def get_tile_type(self, pos):
119         return self._data[pos[1]][pos[0]]
120
121     def set_tile_type(self, pos, new_type):
122         # Setting the type resets any state anyway, so
123         if pos in self._gates:
124             del self._gates[pos]
125         if pos in self._buttons:
126             del self._buttons[pos]
127         self._data[pos[1]][pos[0]] = new_type
128         new_tile = self._get_tile_image(pos, new_type)
129         self._tiles[pos[1]][pos[0]] = new_tile
130         self._changed.append((pos, new_tile))
131         # Also update neighbourhood for wall types, etc.
132         for new_pos in [(pos[0] - 1, pos[1]), (pos[0] + 1, pos[1]),
133                 (pos[0] - 1, pos[1] - 1), (pos[0] + 1, pos[1] + 1),
134                 (pos[0], pos[1] - 1), (pos[0], pos[1] + 1),
135                 (pos[0] - 1, pos[1] + 1), (pos[0] + 1, pos[1] - 1)]:
136             if not self._in_limits(new_pos):
137                 continue
138             # Update display to changed status
139             self._fix_tile(new_pos)
140
141     def _fix_tile(self, pos):
142         tile = self._data[pos[1]][pos[0]]
143         new_tile = self._get_tile_image(pos, tile)
144         self._tiles[pos[1]][pos[0]] = new_tile
145         self._changed.append((pos, new_tile))
146
147     def get_size(self):
148         return len(self._tiles[0]), len(self._tiles)
149
150     def at_exit(self, pos):
151         return pos in self.exit_pos
152
153     def get_level_data(self):
154         return '\n'.join(reversed([''.join(x) for x in self._data]))
155
156     def _get_wall_tile(self, pos):
157         # Is the neighbour in this direction also a wall?
158         x, y = pos
159         left = right = top = bottom = False
160         if x == 0:
161             left = True
162         elif self._data[y][x - 1] == WALL:
163             left = True
164         if x == len(self._data[0]) - 1:
165             right = True
166         elif self._data[y][x + 1] == WALL:
167             right = True
168         if y == 0:
169             top = True
170         elif self._data[y - 1][x] == WALL:
171             top = True
172         if y == len(self._data) - 1:
173             bottom = True
174         elif self._data[y + 1][x] == WALL:
175             bottom = True
176         if top and bottom and left and right:
177             return load_image('tiles/cwall.png')
178         elif bottom and left and right:
179             return load_image('tiles/bottom_wall.png')
180         elif top and left and right:
181             return load_image('tiles/top_wall.png')
182         elif top and bottom and right:
183             return load_image('tiles/left_wall.png')
184         elif top and bottom and left:
185             return load_image('tiles/right_wall.png')
186         elif top and bottom:
187             return load_image('tiles/vert_wall.png')
188         elif left and right:
189             return load_image('tiles/horiz_wall.png')
190         elif left and top:
191             return load_image('tiles/corner_lt.png')
192         elif left and bottom:
193             return load_image('tiles/corner_lb.png')
194         elif right and top:
195             return load_image('tiles/corner_rt.png')
196         elif right and bottom:
197             return load_image('tiles/corner_rb.png')
198         elif top:
199             return load_image('tiles/end_top.png')
200         elif bottom:
201             return load_image('tiles/end_bottom.png')
202         elif left:
203             return load_image('tiles/end_right.png')
204         elif right:
205             return load_image('tiles/end_left.png')
206         return load_image('tiles/pillar.png')
207
208     def _in_limits(self, pos):
209         if pos[0] < 0:
210             return False
211         if pos[1] < 0:
212             return False
213         try:
214             self._data[pos[1]][pos[0]]
215         except IndexError:
216             return False
217         return True
218
219     def blocked(self, pos):
220         if pos[0] < 0:
221             return True
222         if pos[1] < 0:
223             return True
224         try:
225             tile = self._data[pos[1]][pos[0]]
226         except IndexError:
227             return True
228         if tile == WALL or tile == ENTRY:
229             return True
230         if tile == GATE:
231             print tile, pos, self._gates[pos]
232             if self._gates[pos] != -1:
233                 return True
234         return False
235
236     def calc_dist(self, pos1, pos2):
237         return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1])
238
239     def is_gate(self, pos):
240         return self._data[pos[1]][pos[0]] == GATE
241
242     def is_button(self, pos):
243         return self._data[pos[1]][pos[0]] == BUTTON
244
245     def trigger_button(self, pos):
246         if not self.is_button(pos):
247             return False
248         if not self._buttons[pos] == 'active':
249             return False
250         # Find the closest gate down gate and trigger it
251         mindist = 99999
252         gate_pos = None
253         for cand in self._gates:
254             dist = self.calc_dist(pos, cand)
255             if dist < mindist:
256                 gate_pos = cand
257                 mindist = dist
258         if gate_pos:
259             self._buttons[pos] == 'pressed'
260             self._gates[gate_pos] = 3  # Raise gate
261             self._fix_tile(pos)
262             self._fix_tile(gate_pos)
263
264     def damage_gate(self, pos):
265         if not self.is_gate(pos):
266             return False
267         if self._gates[pos] == -1 or self._gates[pos] == 0:
268             return False
269         self._gates[pos] = self._gates[pos] - 1
270         self._fix_gate_tile(pos)
271         self._changed.append((pos, self.get_single_tile(pos)))
272         return True
273
274     def get_changed_tiles(self):
275         ret = self._changed[:]
276         self._changed = []
277         return ret
278
279
280 class LevelList(object):
281
282     LEVELS = 'level_list'
283
284     def __init__(self):
285         self.levels = []
286         self.errors = []
287         level_list = load(self.LEVELS)
288         for line in level_list:
289             line = line.strip()
290             if os.path.exists(filepath(line)):
291                 level_file = load(line)
292                 level = Level(level_file)
293                 level_file.close()
294                 try:
295                     level.validate()
296                     self.levels.append(level)
297                 except RuntimeError as err:
298                     self.errors.append(
299                             'Invalid level %s in level_list: %s' % (line, err))
300             else:
301                 self.errors.append(
302                     'Level list includes non-existant level %s' % line)
303         level_list.close()
304         self._cur_level = 0
305
306     def get_current_level(self):
307         if self._cur_level < len(self.levels):
308             return self.levels[self._cur_level]
309         else:
310             return None
311
312     def get_errors(self):
313         return self.errors
314
315     def advance_to_next_level(self):
316         self._cur_level += 1
317         return self.get_current_level()
318
319     def reset(self):
320         self._cur_level = 0