home · contact · privacy
Refactor change recording; don't regen FOV on non-FOV changes.
[plomrogue2] / plomrogue / things.py
1 from plomrogue.errors import GameError, PlayError
2 from plomrogue.mapping import YX
3 from plomrogue.misc import quote
4 import random
5
6
7
8 class ThingBase:
9     type_ = '?'
10     carrying = False
11
12     def __init__(self, game, id_=0, position=(YX(0, 0), YX(0, 0))):
13         self.game = game
14         if id_ == 0:
15             self.id_ = self.game.new_thing_id()
16         else:
17             self.id_ = id_
18         self.position = position
19
20
21
22 class Thing(ThingBase):
23     blocking = False
24     portable = False
25     protection = '.'
26     commandable = False
27     carried = False
28
29     def __init__(self, *args, **kwargs):
30         super().__init__(*args, **kwargs)
31
32     def proceed(self):
33         pass
34
35     @property
36     def type_(self):
37         return self.__class__.get_type()
38
39     @classmethod
40     def get_type(cls):
41         return cls.__name__[len('Thing_'):]
42
43     def sound(self, name, msg):
44         from plomrogue.mapping import DijkstraMap
45         import re
46
47         def lower_msg_by_volume(msg, volume, largest_audible_distance,
48                                 url_limits = []):
49             import random
50             factor = largest_audible_distance / 4
51             lowered_msg = ''
52             in_url = False
53             i = 0
54             for c in msg:
55                 c = c
56                 if i in url_limits:
57                     in_url = False if in_url else True
58                 if not in_url:
59                     while random.random() > volume * factor:
60                         if c.isupper():
61                             c = c.lower()
62                         elif c != '.' and c != ' ':
63                             c = '.'
64                         else:
65                             c = ' '
66                 lowered_msg += c
67                 i += 1
68             return lowered_msg
69
70         largest_audible_distance = 20
71         # player's don't block sound (or should they?)
72         things = [t for t in self.game.things if t.type_ != 'Player']
73         sound_blockers = self.game.get_sound_blockers()
74         dijkstra_map = DijkstraMap(sound_blockers, things, self.game.maps, self.position,
75                                    largest_audible_distance, self.game.get_map)
76         url_limits = []
77         for m in re.finditer('https?://[^\s]+', msg):
78             url_limits += [m.start(), m.end()]
79         for c_id in self.game.sessions:
80             listener = self.game.get_player(c_id)
81             target_yx = dijkstra_map.target_yx(*listener.position, True)
82             if not target_yx:
83                 continue
84             listener_distance = dijkstra_map[target_yx]
85             if listener_distance > largest_audible_distance:
86                 continue
87             volume = 1 / max(1, listener_distance)
88             lowered_msg = lower_msg_by_volume(msg, volume,
89                                               largest_audible_distance,
90                                               url_limits)
91             lowered_nick = lower_msg_by_volume(name, volume,
92                                                largest_audible_distance)
93             symbol = ''
94             if listener.fov_test(self.position[0], self.position[1]):
95                 self.game.io.send('CHATFACE %s' % self.id_, c_id)
96                 if self.type_ == 'Player' and hasattr(self, 'thing_char'):
97                     symbol = '/@' + self.thing_char
98             self.game.io.send('CHAT ' +
99                               quote('vol:%.f%s %s%s: %s' % (volume * 100, '%',
100                                                             lowered_nick, symbol,
101                                                             lowered_msg)),
102                               c_id)
103
104
105
106 class Thing_Item(Thing):
107     symbol_hint = 'i'
108     portable = True
109
110
111
112 class ThingSpawner(Thing):
113     symbol_hint = 'S'
114
115     def proceed(self):
116         for t in [t for t in self.game.things
117                   if t != self and t.position == self.position]:
118             return
119         self.game.add_thing(self.child_type, self.position)
120         # self.game.changed = True  handled by add_thing
121
122
123
124 class Thing_ItemSpawner(ThingSpawner):
125     child_type = 'Item'
126
127
128
129 class Thing_SpawnPointSpawner(ThingSpawner):
130     child_type = 'SpawnPoint'
131
132
133
134 class Thing_SpawnPoint(Thing):
135     symbol_hint = 's'
136     portable = True
137     name = 'username'
138
139
140
141 class Thing_DoorSpawner(ThingSpawner):
142     child_type = 'Door'
143
144
145
146 class Thing_Door(Thing):
147     symbol_hint = 'D'
148     blocking = False
149     portable = True
150     installable = True
151
152     def open(self):
153         self.blocking = False
154         del self.thing_char
155
156     def close(self):
157         self.blocking = True
158         self.thing_char = '#'
159
160     def install(self):
161         self.portable = False
162
163     def uninstall(self):
164         self.portable = True
165
166
167
168 class Thing_Bottle(Thing):
169     symbol_hint = 'B'
170     portable = True
171     full = True
172     thing_char = '~'
173     spinnable = True
174
175     def empty(self):
176         self.thing_char = '_'
177         self.full = False
178
179     def spin(self):
180         import random
181         all_players = [t for t in self.game.things if t.type_ == 'Player']
182         # TODO: refactor with ThingPlayer.prepare_multiprocessible_fov_stencil
183         # and ThingPlayer.fov_test
184         fov_map_class = self.game.map_geometry.fov_map_class
185         fov_radius = 12
186         light_blockers = self.game.get_light_blockers()
187         fov = fov_map_class(light_blockers, self.game.things, self.game.maps,
188                             self.position, fov_radius, self.game.get_map)
189         fov.init_terrain()
190         visible_players = []
191         for p in all_players:
192             test_position = fov.target_yx(p.position[0], p.position[1])
193             if fov.inside(test_position) and fov[test_position] == '.':
194                 visible_players += [p]
195         if len(visible_players) == 0:
196             self.sound('BOTTLE', 'no visible players in spin range')
197         pick = random.choice(visible_players)
198         self.sound('BOTTLE', 'BOTTLE picks: ' + pick.name)
199
200
201
202 class Thing_BottleSpawner(ThingSpawner):
203     child_type = 'Bottle'
204
205
206
207 class Thing_Hat(Thing):
208     symbol_hint = 'H'
209     portable = True
210     design = ' +--+ ' + ' |  | ' + '======'
211     spinnable = True
212
213     def spin(self):
214         new_design = ''
215         new_design += self.design[12]
216         new_design += self.design[13]
217         new_design += self.design[6]
218         new_design += self.design[7]
219         new_design += self.design[0]
220         new_design += self.design[1]
221         new_design += self.design[14]
222         new_design += self.design[15]
223         new_design += self.design[8]
224         new_design += self.design[9]
225         new_design += self.design[2]
226         new_design += self.design[3]
227         new_design += self.design[16]
228         new_design += self.design[17]
229         new_design += self.design[10]
230         new_design += self.design[11]
231         new_design += self.design[4]
232         new_design += self.design[5]
233         self.design = ''.join(new_design)
234
235
236
237 class Thing_HatRemixer(Thing):
238     symbol_hint = 'H'
239
240     def accept(self, hat):
241         import string
242         new_design = ''
243         legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
244         for i in range(18):
245             new_design += random.choice(list(legal_chars))
246         hat.design = new_design
247         self.sound('HAT REMIXER', 'remixing a hat …')
248         self.game.changed = True
249         self.game.record_change(self.position, 'other')
250
251
252
253 import datetime
254 class Thing_MusicPlayer(Thing):
255     symbol_hint = 'R'
256     commandable = True
257     portable = True
258     repeat = True
259     next_song_start = datetime.datetime.now()
260     playlist_index = -1
261     playing = True
262
263     def __init__(self, *args, **kwargs):
264         super().__init__(*args, **kwargs)
265         self.next_song_start = datetime.datetime.now()
266         self.playlist = []
267
268     def proceed(self):
269         if (not self.playing) or len(self.playlist) == 0:
270             return
271         if datetime.datetime.now() > self.next_song_start:
272             self.playlist_index += 1
273             if self.playlist_index == len(self.playlist):
274                 self.playlist_index = 0
275                 if not self.repeat:
276                     self.playing = False
277                     return
278             song_data = self.playlist[self.playlist_index]
279             self.next_song_start = datetime.datetime.now() +\
280                 datetime.timedelta(seconds=song_data[1])
281             self.sound('MUSICPLAYER', song_data[0])
282             self.game.changed = True
283
284     def interpret(self, command):
285         msg_lines = []
286         if command == 'HELP':
287             msg_lines += ['available commands:']
288             msg_lines += ['HELP – show this help']
289             msg_lines += ['ON/OFF – toggle playback on/off']
290             msg_lines += ['REWIND – return to start of playlist']
291             msg_lines += ['LIST – list programmed songs, durations']
292             msg_lines += ['SKIP – to skip to next song']
293             msg_lines += ['REPEAT – toggle playlist repeat on/off']
294             msg_lines += ['ADD LENGTH SONG – add SONG to playlist, with LENGTH in format "minutes:seconds", i.e. something like "0:47" or "11:02"']
295             return msg_lines
296         elif command == 'LIST':
297             msg_lines += ['playlist:']
298             i = 0
299             for entry in self.playlist:
300                 minutes = entry[1] // 60
301                 seconds = entry[1] % 60
302                 if seconds < 10:
303                     seconds = '0%s' % seconds
304                 selector = 'next:' if i == self.playlist_index else '     '
305                 msg_lines += ['%s %s:%s – %s' % (selector, minutes, seconds, entry[0])]
306                 i += 1
307             return msg_lines
308         elif command == 'ON/OFF':
309             self.playing = False if self.playing else True
310             self.game.changed = True
311             if self.playing:
312                 return ['playing']
313             else:
314                 return ['paused']
315         elif command == 'REMOVE':
316             if len(self.playlist) == 0:
317                 return ['playlist already empty']
318             del self.playlist[max(0, self.playlist_index)]
319             self.playlist_index -= 1
320             if self.playlist_index < -1:
321                 self.playlist_index = -1
322             self.game.changed = True
323             return ['removed song']
324         elif command == 'REWIND':
325             self.playlist_index = -1
326             self.next_song_start = datetime.datetime.now()
327             self.game.changed = True
328             return ['back at start of playlist']
329         elif command == 'SKIP':
330             self.next_song_start = datetime.datetime.now()
331             self.game.changed = True
332             return ['skipped']
333         elif command == 'REPEAT':
334             self.repeat = False if self.repeat else True
335             self.game.changed = True
336             if self.repeat:
337                 return ['playlist repeat turned on']
338             else:
339                 return ['playlist repeat turned off']
340         elif command.startswith('ADD '):
341             tokens = command.split(' ', 2)
342             if len(tokens) != 3:
343                 return ['wrong syntax, see HELP']
344             length = tokens[1].split(':')
345             if len(length) != 2:
346                 return ['wrong syntax, see HELP']
347             try:
348                 minutes = int(length[0])
349                 seconds = int(length[1])
350             except ValueError:
351                 return ['wrong syntax, see HELP']
352             self.playlist += [(tokens[2], minutes * 60 + seconds)]
353             self.game.changed = True
354             return ['added']
355         else:
356             return ['cannot understand command']
357
358
359
360 class Thing_BottleDeposit(Thing):
361     bottle_counter = 0
362     symbol_hint = 'O'
363
364     def proceed(self):
365         if self.bottle_counter >= 3:
366             self.bottle_counter = 0
367             choice = random.choice(['MusicPlayer', 'Hat'])
368             self.game.add_thing(choice, self.position)
369             msg = 'here is a gift as a reward for ecological consciousness –'
370             if choice == 'MusicPlayer':
371                 msg += 'pick it up and then use "command thing" on it!'
372             elif choice == 'Hat':
373                 msg += 'pick it up and then use "(un-)wear" on it!'
374             self.sound('BOTTLE DEPOSITOR', msg)
375             # self.game.changed = True  done by game.add_thing
376
377     def accept(self):
378         self.bottle_counter += 1
379         self.sound('BOTTLE DEPOSITOR',
380                    'thanks for this empty bottle – deposit %s more for a gift!' %
381                    (3 - self.bottle_counter))
382
383
384
385 class Thing_Cookie(Thing):
386     symbol_hint = 'c'
387     portable = True
388
389     def __init__(self, *args, **kwargs):
390         import string
391         super().__init__(*args, **kwargs)
392         legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
393         self.thing_char = random.choice(list(legal_chars))
394
395
396
397 class Thing_CookieSpawner(Thing):
398     symbol_hint = 'O'
399
400     def accept(self, thing):
401         self.sound('OVEN', '*heat* *brrzt* here\'s a cookie!')
402         self.game.add_thing('Cookie', self.position)
403
404
405
406 class ThingAnimate(Thing):
407     blocking = True
408     drunk = 0
409
410     def __init__(self, *args, **kwargs):
411         super().__init__(*args, **kwargs)
412         self.next_task = [None]
413         self.task = None
414         self.invalidate('fov')
415         self.invalidate('other')  # currently redundant though
416
417     def invalidate(self, type_):
418         if type_ == 'fov':
419             self._fov = None
420             self._visible_terrain = None
421             self._visible_control = None
422             self.invalidate('other')
423         elif type_ == 'other':
424             self._seen_things = None
425             self._seen_annotation_positions = None
426             self._seen_portal_positions = None
427
428     def set_next_task(self, task_name, args=()):
429         task_class = self.game.tasks[task_name]
430         self.next_task = [task_class(self, args)]
431
432     def get_next_task(self):
433         if self.next_task[0]:
434             task = self.next_task[0]
435             self.next_task = [None]
436             task.check()
437             return task
438
439     def proceed(self):
440         self.drunk -= 1
441         if self.drunk == 0:
442             for c_id in self.game.sessions:
443                 if self.game.sessions[c_id]['thing_id'] == self.id_:
444                     # TODO: refactor with self.send_msg
445                     self.game.io.send('DEFAULT_COLORS', c_id)
446                     self.game.io.send('CHAT "You sober up."', c_id)
447                     self.invalidate('fov')
448                     break
449             self.game.changed = True
450         if self.task is None:
451             self.task = self.get_next_task()
452             return
453         try:
454             self.task.check()
455         except (PlayError, GameError) as e:
456             self.task = None
457             raise e
458         self.task.todo -= 1
459         if self.task.todo <= 0:
460             self.task.do()
461             self.game.changed = True
462             self.task = self.get_next_task()
463
464     def prepare_multiprocessible_fov_stencil(self):
465         fov_map_class = self.game.map_geometry.fov_map_class
466         fov_radius = 3 if self.drunk > 0 else 12
467         light_blockers = self.game.get_light_blockers()
468         self._fov = fov_map_class(light_blockers, self.game.things, self.game.maps,
469                                   self.position, fov_radius, self.game.get_map)
470
471     def multiprocessible_fov_stencil(self):
472         self._fov.init_terrain()
473
474     @property
475     def fov_stencil(self):
476         if self._fov:
477             return self._fov
478         # due to the pre-multiprocessing in game.send_gamestate,
479         # the following should actually never be called
480         self.prepare_multiprocessible_fov_stencil()
481         self.multiprocessible_fov_stencil()
482         return self._fov
483
484     def fov_stencil_make(self):
485         self._fov.make()
486
487     def fov_test(self, big_yx, little_yx):
488         test_position = self.fov_stencil.target_yx(big_yx, little_yx)
489         if self.fov_stencil.inside(test_position):
490             if self.fov_stencil[test_position] == '.':
491                 return True
492         return False
493
494     def fov_stencil_map(self, map_type):
495         visible_terrain = ''
496         for yx in self.fov_stencil:
497             if self.fov_stencil[yx] == '.':
498                 big_yx, little_yx = self.fov_stencil.source_yxyx(yx)
499                 map_ = self.game.get_map(big_yx, map_type)
500                 visible_terrain += map_[little_yx]
501             else:
502                 visible_terrain += ' '
503         return visible_terrain
504
505     @property
506     def visible_terrain(self):
507         if self._visible_terrain:
508             return self._visible_terrain
509         self._visible_terrain = self.fov_stencil_map('normal')
510         return self._visible_terrain
511
512     @property
513     def visible_control(self):
514         if self._visible_control:
515             return self._visible_control
516         self._visible_control = self.fov_stencil_map('control')
517         return self._visible_control
518
519     @property
520     def seen_things(self):
521         if self._seen_things is not None:
522             return self._seen_things
523         self._seen_things = [t for t in self.game.things
524                              if self.fov_test(*t.position)]
525         return self._seen_things
526
527     @property
528     def seen_annotation_positions(self):
529         if self._seen_annotation_positions is not None:
530             return self._seen_annotation_positions
531         self._seen_annotation_positions = []
532         for big_yx in self.game.annotations:
533             for little_yx in [little_yx for little_yx
534                               in self.game.annotations[big_yx]
535                               if self.fov_test(big_yx, little_yx)]:
536                 self._seen_annotation_positions += [(big_yx, little_yx)]
537         return self._seen_annotation_positions
538
539     @property
540     def seen_portal_positions(self):
541         if self._seen_portal_positions is not None:
542             return self._seen_portal_positions
543         self._seen_portal_positions = []
544         for big_yx in self.game.portals:
545             for little_yx in [little_yx for little_yx
546                               in self.game.portals[big_yx]
547                               if self.fov_test(big_yx, little_yx)]:
548                 self._seen_portal_positions += [(big_yx, little_yx)]
549         return self._seen_portal_positions
550
551
552
553 class Thing_Player(ThingAnimate):
554     symbol_hint = '@'
555
556     def __init__(self, *args, **kwargs):
557         super().__init__(*args, **kwargs)
558         self.carrying = None
559
560     def send_msg(self, msg):
561         for c_id in self.game.sessions:
562             if self.game.sessions[c_id]['thing_id'] == self.id_:
563                 self.game.io.send(msg, c_id)
564                 break
565
566     def uncarry(self):
567         t = self.carrying
568         t.carried = False
569         self.carrying = None
570         return t
571
572     def add_cookie_char(self, c):
573         if not self.name in self.game.players_hat_chars:
574             self.game.players_hat_chars[self.name] = ' #'  # default
575         if not c in self.game.players_hat_chars[self.name]:
576             self.game.players_hat_chars[self.name] += c
577
578     def get_cookie_chars(self):
579         if self.name in self.game.players_hat_chars:
580             return self.game.players_hat_chars[self.name]
581         return ' #'  # default