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