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