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