home · contact · privacy
a0db94a0f639907d0cd1d35169c8d77cf3e19b9f
[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 ThingAnimate(Thing):
460     weariness = 0
461
462     def __init__(self, *args, **kwargs):
463         super().__init__(*args, **kwargs)
464         self.next_task = [None]
465         self.task = None
466         self.invalidate('fov')
467         self.invalidate('other')  # currently redundant though
468
469     def invalidate(self, type_):
470         if type_ == 'fov':
471             self._fov = None
472             self._visible_terrain = None
473             self._visible_control = None
474             self.invalidate('other')
475         elif type_ == 'other':
476             self._seen_things = None
477             self._seen_annotation_positions = None
478             self._seen_portal_positions = None
479
480     def set_next_task(self, task_name, args=()):
481         task_class = self.game.tasks[task_name]
482         self.next_task = [task_class(self, args)]
483
484     def get_next_task(self):
485         if self.next_task[0]:
486             task = self.next_task[0]
487             self.next_task = [None]
488             task.check()
489             task.todo += self.weariness * 10
490             return task
491
492     def proceed(self):
493         if self.task is None:
494             self.task = self.get_next_task()
495             return
496         try:
497             self.task.check()
498         except (PlayError, GameError) as e:
499             self.task = None
500             raise e
501         self.task.todo -= 1
502         if self.task.todo <= 0:
503             self.task.do()
504             self.game.changed = True
505             self.task = self.get_next_task()
506
507     def prepare_multiprocessible_fov_stencil(self):
508         fov_radius = 3 if self.drunk > 0 else 12
509         light_blockers = self.game.get_light_blockers()
510         obstacles = [t.position for t in self.game.things if t.blocks_light]
511         self._fov = FovMap(light_blockers, obstacles, self.game.maps,
512                            self.position, fov_radius, self.game.get_map)
513
514     def multiprocessible_fov_stencil(self):
515         self._fov.init_terrain()
516
517     @property
518     def fov_stencil(self):
519         if self._fov:
520             return self._fov
521         # due to the pre-multiprocessing in game.send_gamestate,
522         # the following should actually never be called
523         self.prepare_multiprocessible_fov_stencil()
524         self.multiprocessible_fov_stencil()
525         return self._fov
526
527     def fov_test(self, big_yx, little_yx):
528         test_position = self.fov_stencil.target_yx(big_yx, little_yx)
529         if self.fov_stencil.inside(test_position):
530             if self.fov_stencil[test_position] == '.':
531                 return True
532         return False
533
534     def fov_stencil_map(self, map_type):
535         visible_terrain = ''
536         for yx in self.fov_stencil:
537             if self.fov_stencil[yx] == '.':
538                 big_yx, little_yx = self.fov_stencil.source_yxyx(yx)
539                 map_ = self.game.get_map(big_yx, map_type)
540                 visible_terrain += map_[little_yx]
541             else:
542                 visible_terrain += ' '
543         return visible_terrain
544
545     @property
546     def visible_terrain(self):
547         if self._visible_terrain:
548             return self._visible_terrain
549         self._visible_terrain = self.fov_stencil_map('normal')
550         return self._visible_terrain
551
552     @property
553     def visible_control(self):
554         if self._visible_control:
555             return self._visible_control
556         self._visible_control = self.fov_stencil_map('control')
557         return self._visible_control
558
559     @property
560     def seen_things(self):
561         if self._seen_things is not None:
562             return self._seen_things
563         self._seen_things = [t for t in self.game.things
564                              if self.fov_test(*t.position)]
565         return self._seen_things
566
567     @property
568     def seen_annotation_positions(self):
569         if self._seen_annotation_positions is not None:
570             return self._seen_annotation_positions
571         self._seen_annotation_positions = []
572         for big_yx in self.game.annotations:
573             for little_yx in [little_yx for little_yx
574                               in self.game.annotations[big_yx]
575                               if self.fov_test(big_yx, little_yx)]:
576                 self._seen_annotation_positions += [(big_yx, little_yx)]
577         return self._seen_annotation_positions
578
579     @property
580     def seen_portal_positions(self):
581         if self._seen_portal_positions is not None:
582             return self._seen_portal_positions
583         self._seen_portal_positions = []
584         for big_yx in self.game.portals:
585             for little_yx in [little_yx for little_yx
586                               in self.game.portals[big_yx]
587                               if self.fov_test(big_yx, little_yx)]:
588                 self._seen_portal_positions += [(big_yx, little_yx)]
589         return self._seen_portal_positions
590
591
592
593 class Thing_Player(ThingAnimate):
594     symbol_hint = '@'
595     drunk = 0
596     tripping = 0
597     need_for_toilet = 0
598     standing = True
599
600     def __init__(self, *args, **kwargs):
601         super().__init__(*args, **kwargs)
602         self.carrying = None
603
604     def proceed(self):
605         super().proceed()
606         if self.drunk >= 0:
607             self.drunk -= 1
608         if self.tripping >= 0:
609             self.tripping -= 1
610         if self.need_for_toilet > 0:
611             terrain = self.game.maps[self.position[0]][self.position[1]]
612             if terrain in self.game.terrains:
613                 terrain_type = self.game.terrains[terrain]
614                 if 'toilet' in terrain_type.tags:
615                     self.send_msg('CHAT "You use the toilet. What a relief!"')
616                     self.need_for_toilet = 0
617         if self.need_for_toilet > 0:
618             if random.random() > 0.9999:
619                 self.need_for_toilet += 1
620                 self.game.changed = True
621             if 100000 * random.random() < self.need_for_toilet:
622                 self.send_msg('CHAT "You need to go to a toilet."')
623             if self.need_for_toilet > 100:
624                 self.send_msg('CHAT "You pee into your pants. Eww!"')
625                 self.need_for_toilet = 0
626                 self.game.changed = True
627         if self.drunk == 0:
628             self.send_msg('CHAT "You sober up."')
629             self.invalidate('fov')
630             self.game.changed = True
631         if self.tripping == 0:
632             self.send_msg('DEFAULT_COLORS')
633             self.send_msg('CHAT "You sober up."')
634             self.game.changed = True
635         elif self.tripping > 0 and self.tripping % 250 == 0:
636             self.send_msg('RANDOM_COLORS')
637             self.game.changed = True
638         if random.random() > 0.9999:
639             if self.standing:
640                 self.weariness += 1
641                 if self.weariness % 5 == 0:
642                     self.send_msg('CHAT "All that walking or standing makes '
643                                   'you weary, and thereby slower. Find a place '
644                                   'to sit or lie down to regain energy."')
645             elif self.weariness > 0:
646                 self.weariness -= 1
647             self.game.changed = True
648
649     def send_msg(self, msg):
650         for c_id in self.game.sessions:
651             if self.game.sessions[c_id]['thing_id'] == self.id_:
652                 self.game.io.send(msg, c_id)
653                 break
654
655     def uncarry(self):
656         t = self.carrying
657         t.carried = False
658         self.carrying = None
659         return t
660
661     def add_cookie_char(self, c):
662         if not self.name in self.game.players_hat_chars:
663             self.game.players_hat_chars[self.name] = ' #'  # default
664         if not c in self.game.players_hat_chars[self.name]:
665             self.game.players_hat_chars[self.name] += c
666
667     def get_cookie_chars(self):
668         chars = ' #'  # default
669         if self.name in self.game.players_hat_chars:
670             chars = self.game.players_hat_chars[self.name]
671         chars_split = list(chars)
672         chars_split.sort()
673         return ''.join(chars_split)