home · contact · privacy
Recalc FOVs and their map view results only on relevant changes.
[plomrogue2] / plomrogue / things.py
1 from plomrogue.errors import GameError, PlayError
2 from plomrogue.mapping import YX
3 import random
4
5
6
7 class ThingBase:
8     type_ = '?'
9
10     def __init__(self, game, id_=0, position=(YX(0, 0), YX(0, 0))):
11         self.game = game
12         if id_ == 0:
13             self.id_ = self.game.new_thing_id()
14         else:
15             self.id_ = id_
16         self.position = position
17
18
19
20 class Thing(ThingBase):
21     blocking = False
22     portable = False
23     protection = '.'
24     commandable = False
25
26     def __init__(self, *args, **kwargs):
27         super().__init__(*args, **kwargs)
28
29     def proceed(self):
30         pass
31
32     @property
33     def type_(self):
34         return self.__class__.get_type()
35
36     @classmethod
37     def get_type(cls):
38         return cls.__name__[len('Thing_'):]
39
40     def sound(self, name, msg):
41         from plomrogue.mapping import DijkstraMap
42         from plomrogue.misc import quote
43
44         def lower_msg_by_volume(msg, volume, largest_audible_distance):
45             import random
46             factor = largest_audible_distance / 4
47             lowered_msg = ''
48             for c in msg:
49                 c = c
50                 while random.random() > volume * factor:
51                     if c.isupper():
52                         c = c.lower()
53                     elif c != '.' and c != ' ':
54                         c = '.'
55                     else:
56                         c = ' '
57                 lowered_msg += c
58             return lowered_msg
59
60         largest_audible_distance = 20
61         # player's don't block sound (or should they?)
62         things = [t for t in self.game.things if t.type_ != 'Player']
63         dijkstra_map = DijkstraMap(things, self.game.maps, self.position,
64                                    largest_audible_distance, self.game.get_map)
65         for c_id in self.game.sessions:
66             listener = self.game.get_player(c_id)
67             target_yx = dijkstra_map.target_yx(*listener.position, True)
68             if not target_yx:
69                 continue
70             listener_distance = dijkstra_map[target_yx]
71             if listener_distance > largest_audible_distance:
72                 continue
73             volume = 1 / max(1, listener_distance)
74             lowered_msg = lower_msg_by_volume(msg, volume,
75                                               largest_audible_distance)
76             lowered_nick = lower_msg_by_volume(name, volume,
77                                                largest_audible_distance)
78             self.game.io.send('CHAT ' +
79                               quote('(volume: %.2f) %s: %s' % (volume,
80                                                                lowered_nick,
81                                                                lowered_msg)),
82                               c_id)
83
84
85
86 class Thing_Item(Thing):
87     symbol_hint = 'i'
88     portable = True
89
90
91
92 class ThingSpawner(Thing):
93     symbol_hint = 'S'
94
95     def proceed(self):
96         for t in [t for t in self.game.things
97                   if t != self and t.position == self.position]:
98             return
99         t = self.game.thing_types[self.child_type](self.game,
100                                                    position=self.position)
101         self.game.things += [t]
102         self.game.changed = True
103         self.game.changed_fovs = True
104
105
106
107 class Thing_ItemSpawner(ThingSpawner):
108     child_type = 'Item'
109
110
111
112 class Thing_SpawnPointSpawner(ThingSpawner):
113     child_type = 'SpawnPoint'
114
115
116
117 class Thing_SpawnPoint(Thing):
118     symbol_hint = 's'
119     portable = True
120     name = 'username'
121
122
123
124 class Thing_DoorSpawner(ThingSpawner):
125     child_type = 'Door'
126
127
128
129 class Thing_Door(Thing):
130     symbol_hint = 'D'
131     blocking = False
132     portable = True
133     installable = True
134
135     def open(self):
136         self.blocking = False
137         del self.thing_char
138
139     def close(self):
140         self.blocking = True
141         self.thing_char = '#'
142
143     def install(self):
144         self.portable = False
145
146     def uninstall(self):
147         self.portable = True
148
149
150
151 class Thing_Bottle(Thing):
152     symbol_hint = 'B'
153     portable = True
154     full = True
155     thing_char = '~'
156
157     def empty(self):
158         self.thing_char = '_'
159         self.full = False
160
161
162
163 class Thing_BottleSpawner(ThingSpawner):
164     child_type = 'Bottle'
165
166
167
168 class Thing_Hat(Thing):
169     symbol_hint = 'H'
170     portable = True
171     design = ' +--+ ' + ' |  | ' + '======'
172
173
174
175 class Thing_HatRemixer(Thing):
176     symbol_hint = 'H'
177
178     def accept(self, hat):
179         import string
180         new_design = ''
181         legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
182         for i in range(18):
183             new_design += random.choice(list(legal_chars))
184         hat.design = new_design
185         self.sound('HAT REMIXER', 'remixing a hat …')
186         self.game.changed = True
187
188
189
190 import datetime
191 class Thing_MusicPlayer(Thing):
192     symbol_hint = 'R'
193     commandable = True
194     portable = True
195     repeat = True
196     next_song_start = datetime.datetime.now()
197     playlist_index = -1
198     playing = True
199
200     def __init__(self, *args, **kwargs):
201         super().__init__(*args, **kwargs)
202         self.next_song_start = datetime.datetime.now()
203         self.playlist = []
204
205     def proceed(self):
206         if (not self.playing) or len(self.playlist) == 0:
207             return
208         if datetime.datetime.now() > self.next_song_start:
209             self.playlist_index += 1
210             if self.playlist_index == len(self.playlist):
211                 self.playlist_index = 0
212                 if not self.repeat:
213                     self.playing = False
214                     return
215             song_data = self.playlist[self.playlist_index]
216             self.next_song_start = datetime.datetime.now() +\
217                 datetime.timedelta(seconds=song_data[1])
218             self.sound('MUSICPLAYER', song_data[0])
219             self.game.changed = True
220
221     def interpret(self, command):
222         msg_lines = []
223         if command == 'HELP':
224             msg_lines += ['available commands:']
225             msg_lines += ['HELP – show this help']
226             msg_lines += ['ON/OFF – toggle playback on/off']
227             msg_lines += ['REWIND – return to start of playlist']
228             msg_lines += ['LIST – list programmed songs, durations']
229             msg_lines += ['SKIP – to skip to next song']
230             msg_lines += ['REPEAT – toggle playlist repeat on/off']
231             msg_lines += ['ADD LENGTH SONG – add SONG to playlist, with LENGTH in format "minutes:seconds", i.e. something like "0:47" or "11:02"']
232             return msg_lines
233         elif command == 'LIST':
234             msg_lines += ['playlist:']
235             i = 0
236             for entry in self.playlist:
237                 minutes = entry[1] // 60
238                 seconds = entry[1] % 60
239                 if seconds < 10:
240                     seconds = '0%s' % seconds
241                 selector = 'next:' if i == self.playlist_index else '     '
242                 msg_lines += ['%s %s:%s – %s' % (selector, minutes, seconds, entry[0])]
243                 i += 1
244             return msg_lines
245         elif command == 'ON/OFF':
246             self.playing = False if self.playing else True
247             self.game.changed = True
248             if self.playing:
249                 return ['playing']
250             else:
251                 return ['paused']
252         elif command == 'REMOVE':
253             if len(self.playlist) == 0:
254                 return ['playlist already empty']
255             del self.playlist[max(0, self.playlist_index)]
256             self.playlist_index -= 1
257             if self.playlist_index < -1:
258                 self.playlist_index = -1
259             self.game.changed = True
260             return ['removed song']
261         elif command == 'REWIND':
262             self.playlist_index = -1
263             self.next_song_start = datetime.datetime.now()
264             self.game.changed = True
265             return ['back at start of playlist']
266         elif command == 'SKIP':
267             self.next_song_start = datetime.datetime.now()
268             self.game.changed = True
269             return ['skipped']
270         elif command == 'REPEAT':
271             self.repeat = False if self.repeat else True
272             self.game.changed = True
273             if self.repeat:
274                 return ['playlist repeat turned on']
275             else:
276                 return ['playlist repeat turned off']
277         elif command.startswith('ADD '):
278             tokens = command.split(' ', 2)
279             if len(tokens) != 3:
280                 return ['wrong syntax, see HELP']
281             length = tokens[1].split(':')
282             if len(length) != 2:
283                 return ['wrong syntax, see HELP']
284             try:
285                 minutes = int(length[0])
286                 seconds = int(length[1])
287             except ValueError:
288                 return ['wrong syntax, see HELP']
289             self.playlist += [(tokens[2], minutes * 60 + seconds)]
290             self.game.changed = True
291             return ['added']
292         else:
293             return ['cannot understand command']
294
295
296
297 class Thing_BottleDeposit(Thing):
298     bottle_counter = 0
299     symbol_hint = 'O'
300
301     def proceed(self):
302         if self.bottle_counter >= 3:
303             self.bottle_counter = 0
304             choice = random.choice(['MusicPlayer', 'Hat'])
305             t = self.game.thing_types[choice](self.game, position=self.position)
306             self.game.things += [t]
307             msg = 'here is a gift as a reward for ecological consciousness –'
308             if choice == 'MusicPlayer':
309                 msg += 'pick it up and then use "command thing" on it!'
310             elif choice == 'Hat':
311                 msg += 'pick it up and then use "(un-)wear" on it!'
312             self.sound('BOTTLE DEPOSITOR', msg)
313             self.game.changed = True
314             self.game.changed_fovs = True
315
316     def accept(self):
317         self.bottle_counter += 1
318         self.sound('BOTTLE DEPOSITOR',
319                    'thanks for this empty bottle – deposit %s more for a gift!' %
320                    (3 - self.bottle_counter))
321
322
323
324
325 class ThingAnimate(Thing):
326     blocking = True
327     drunk = 0
328
329     def __init__(self, *args, **kwargs):
330         super().__init__(*args, **kwargs)
331         self.next_task = [None]
332         self.task = None
333         self.invalidate_map_view()
334
335     def invalidate_map_view(self):
336         self._fov = None
337         self._visible_terrain = None
338         self._visible_control = None
339
340     def set_next_task(self, task_name, args=()):
341         task_class = self.game.tasks[task_name]
342         self.next_task = [task_class(self, args)]
343
344     def get_next_task(self):
345         if self.next_task[0]:
346             task = self.next_task[0]
347             self.next_task = [None]
348             task.check()
349             return task
350
351     def proceed(self):
352         self.drunk -= 1
353         if self.drunk == 0:
354             for c_id in self.game.sessions:
355                 if self.game.sessions[c_id]['thing_id'] == self.id_:
356                     # TODO: refactor with self.send_msg
357                     self.game.io.send('DEFAULT_COLORS', c_id)
358                     self.game.io.send('CHAT "You sober up."', c_id)
359                     self.game.changed_fovs = True
360                     break
361             self.game.changed = True
362         if self.task is None:
363             self.task = self.get_next_task()
364             return
365         try:
366             self.task.check()
367         except (PlayError, GameError) as e:
368             self.task = None
369             raise e
370         self.task.todo -= 1
371         if self.task.todo <= 0:
372             self.task.do()
373             self.game.changed = True
374             self.task = self.get_next_task()
375
376     def prepare_multiprocessible_fov_stencil(self):
377         fov_map_class = self.game.map_geometry.fov_map_class
378         fov_radius = 3 if self.drunk > 0 else 12
379         self._fov = fov_map_class(self.game.things, self.game.maps,
380                                   self.position, fov_radius, self.game.get_map)
381
382     def multiprocessible_fov_stencil(self):
383         self._fov.init_terrain()
384
385     @property
386     def fov_stencil(self):
387         if self._fov:
388             return self._fov
389         # due to the pre-multiprocessing in game.send_gamestate,
390         # the following should actually never be called
391         self.prepare_multiprocessible_fov_stencil()
392         self.multiprocessible_fov_stencil()
393         return self._fov
394
395     def fov_stencil_make(self):
396         self._fov.make()
397
398     def fov_test(self, big_yx, little_yx):
399         test_position = self.fov_stencil.target_yx(big_yx, little_yx)
400         if self.fov_stencil.inside(test_position):
401             if self.fov_stencil[test_position] == '.':
402                 return True
403         return False
404
405     def fov_stencil_map(self, map_type):
406         visible_terrain = ''
407         for yx in self.fov_stencil:
408             if self.fov_stencil[yx] == '.':
409                 big_yx, little_yx = self.fov_stencil.source_yxyx(yx)
410                 map_ = self.game.get_map(big_yx, map_type)
411                 visible_terrain += map_[little_yx]
412             else:
413                 visible_terrain += ' '
414         return visible_terrain
415
416     @property
417     def visible_terrain(self):
418         if self._visible_terrain:
419             return self._visible_terrain
420         self._visible_terrain = self.fov_stencil_map('normal')
421         return self._visible_terrain
422
423     @property
424     def visible_control(self):
425         if self._visible_control:
426             return self._visible_control
427         self._visible_control = self.fov_stencil_map('control')
428         return self._visible_control
429
430
431
432 class Thing_Player(ThingAnimate):
433     symbol_hint = '@'
434
435     def __init__(self, *args, **kwargs):
436         super().__init__(*args, **kwargs)
437         self.carrying = None
438
439     def send_msg(self, msg):
440         for c_id in self.game.sessions:
441             if self.game.sessions[c_id]['thing_id'] == self.id_:
442                 self.game.io.send(msg, c_id)
443                 break