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