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