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