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