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