home · contact · privacy
072f2513ce9a11a56e86c92828cbfde3cb1f594b
[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             import random
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         sound_blockers = self.game.get_sound_blockers()
75         dijkstra_map = DijkstraMap(sound_blockers, obstacles, self.game.maps,
76                                    self.position, largest_audible_distance,
77                                    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                 self.game.io.send('CHATFACE %s' % self.id_, c_id)
98                 if self.type_ == 'Player' and hasattr(self, 'thing_char'):
99                     symbol = '/@' + self.thing_char
100             self.game.io.send('CHAT ' +
101                               quote('vol:%.f%s %s%s: %s' % (volume * 100, '%',
102                                                             lowered_nick, symbol,
103                                                             lowered_msg)),
104                               c_id)
105
106
107
108 class Thing_Item(Thing):
109     symbol_hint = 'i'
110     portable = True
111
112
113
114 class ThingSpawner(Thing):
115     symbol_hint = 'S'
116
117     def proceed(self):
118         for t in [t for t in self.game.things
119                   if t != self and t.position == self.position]:
120             return
121         self.game.add_thing(self.child_type, self.position)
122
123
124
125 class Thing_ItemSpawner(ThingSpawner):
126     child_type = 'Item'
127
128
129
130 class Thing_SpawnPointSpawner(ThingSpawner):
131     child_type = 'SpawnPoint'
132
133
134
135 class Thing_SpawnPoint(Thing):
136     symbol_hint = 's'
137     portable = True
138     name = 'username'
139
140
141
142 class Thing_DoorSpawner(ThingSpawner):
143     child_type = 'Door'
144
145
146
147 class Thing_Door(Thing):
148     symbol_hint = 'D'
149     blocks_movement = False
150     portable = True
151     installable = True
152
153     def open(self):
154         self.blocks_movement = False
155         self.blocks_light = False
156         self.blocks_sound = False
157         del self.thing_char
158
159     def close(self):
160         self.blocks_movement = True
161         self.blocks_light = True
162         self.blocks_sound = True
163         self.thing_char = '#'
164
165     def install(self):
166         self.portable = False
167
168     def uninstall(self):
169         self.portable = True
170
171
172
173 class Thing_Psychedelic(Thing):
174     symbol_hint = 'P'
175     portable = True
176
177
178
179 class Thing_PsychedelicSpawner(ThingSpawner):
180     symbol_hint = 'P'
181     child_type = 'Psychedelic'
182
183
184
185 class Thing_Bottle(Thing):
186     symbol_hint = 'B'
187     portable = True
188     full = True
189     thing_char = '~'
190     spinnable = True
191
192     def empty(self):
193         self.thing_char = '_'
194         self.full = False
195
196     def spin(self):
197         import random
198         all_players = [t for t in self.game.things if t.type_ == 'Player']
199         # TODO: refactor with ThingPlayer.prepare_multiprocessible_fov_stencil
200         # and ThingPlayer.fov_test
201         fov_map_class = self.game.map_geometry.fov_map_class
202         fov_radius = 12
203         light_blockers = self.game.get_light_blockers()
204         obstacles = [t.position for t in self.game.things if t.blocks_light]
205         fov = fov_map_class(light_blockers, obstacles, self.game.maps,
206                             self.position, fov_radius, self.game.get_map)
207         fov.init_terrain()
208         visible_players = []
209         for p in all_players:
210             test_position = fov.target_yx(p.position[0], p.position[1])
211             if fov.inside(test_position) and fov[test_position] == '.':
212                 visible_players += [p]
213         if len(visible_players) == 0:
214             self.sound('BOTTLE', 'no visible players in spin range')
215         pick = random.choice(visible_players)
216         self.sound('BOTTLE', 'BOTTLE picks: ' + pick.name)
217
218
219
220 class Thing_BottleSpawner(ThingSpawner):
221     child_type = 'Bottle'
222
223
224
225 class Thing_Hat(Thing):
226     symbol_hint = 'H'
227     portable = True
228     design = ' +--+ ' + ' |  | ' + '======'
229     spinnable = True
230
231     def spin(self):
232         new_design = ''
233         new_design += self.design[12]
234         new_design += self.design[13]
235         new_design += self.design[6]
236         new_design += self.design[7]
237         new_design += self.design[0]
238         new_design += self.design[1]
239         new_design += self.design[14]
240         new_design += self.design[15]
241         new_design += self.design[8]
242         new_design += self.design[9]
243         new_design += self.design[2]
244         new_design += self.design[3]
245         new_design += self.design[16]
246         new_design += self.design[17]
247         new_design += self.design[10]
248         new_design += self.design[11]
249         new_design += self.design[4]
250         new_design += self.design[5]
251         self.design = ''.join(new_design)
252
253
254
255 class Thing_HatRemixer(Thing):
256     symbol_hint = 'H'
257
258     def accept(self, hat):
259         import string
260         new_design = ''
261         legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
262         for i in range(18):
263             new_design += random.choice(list(legal_chars))
264         hat.design = new_design
265         self.sound('HAT REMIXER', 'remixing a hat …')
266         self.game.changed = True
267         self.game.record_change(self.position, 'other')
268
269
270
271 import datetime
272 class Thing_MusicPlayer(Thing):
273     symbol_hint = 'R'
274     commandable = True
275     portable = True
276     repeat = True
277     next_song_start = datetime.datetime.now()
278     playlist_index = -1
279     playing = True
280
281     def __init__(self, *args, **kwargs):
282         super().__init__(*args, **kwargs)
283         self.next_song_start = datetime.datetime.now()
284         self.playlist = []
285
286     def proceed(self):
287         if (not self.playing) or len(self.playlist) == 0:
288             return
289         if datetime.datetime.now() > self.next_song_start:
290             self.playlist_index += 1
291             if self.playlist_index == len(self.playlist):
292                 self.playlist_index = 0
293                 if not self.repeat:
294                     self.playing = False
295                     return
296             song_data = self.playlist[self.playlist_index]
297             self.next_song_start = datetime.datetime.now() +\
298                 datetime.timedelta(seconds=song_data[1])
299             self.sound('MUSICPLAYER', song_data[0])
300             self.game.changed = True
301
302     def interpret(self, command):
303         msg_lines = []
304         if command == 'HELP':
305             msg_lines += ['available commands:']
306             msg_lines += ['HELP – show this help']
307             msg_lines += ['ON/OFF – toggle playback on/off']
308             msg_lines += ['REWIND – return to start of playlist']
309             msg_lines += ['LIST – list programmed songs, durations']
310             msg_lines += ['SKIP – to skip to next song']
311             msg_lines += ['REPEAT – toggle playlist repeat on/off']
312             msg_lines += ['ADD LENGTH SONG – add SONG to playlist, with LENGTH in format "minutes:seconds", i.e. something like "0:47" or "11:02"']
313             return msg_lines
314         elif command == 'LIST':
315             msg_lines += ['playlist:']
316             i = 0
317             for entry in self.playlist:
318                 minutes = entry[1] // 60
319                 seconds = entry[1] % 60
320                 if seconds < 10:
321                     seconds = '0%s' % seconds
322                 selector = 'next:' if i == self.playlist_index else '     '
323                 msg_lines += ['%s %s:%s – %s' % (selector, minutes, seconds, entry[0])]
324                 i += 1
325             return msg_lines
326         elif command == 'ON/OFF':
327             self.playing = False if self.playing else True
328             self.game.changed = True
329             if self.playing:
330                 return ['playing']
331             else:
332                 return ['paused']
333         elif command == 'REMOVE':
334             if len(self.playlist) == 0:
335                 return ['playlist already empty']
336             del self.playlist[max(0, self.playlist_index)]
337             self.playlist_index -= 1
338             if self.playlist_index < -1:
339                 self.playlist_index = -1
340             self.game.changed = True
341             return ['removed song']
342         elif command == 'REWIND':
343             self.playlist_index = -1
344             self.next_song_start = datetime.datetime.now()
345             self.game.changed = True
346             return ['back at start of playlist']
347         elif command == 'SKIP':
348             self.next_song_start = datetime.datetime.now()
349             self.game.changed = True
350             return ['skipped']
351         elif command == 'REPEAT':
352             self.repeat = False if self.repeat else True
353             self.game.changed = True
354             if self.repeat:
355                 return ['playlist repeat turned on']
356             else:
357                 return ['playlist repeat turned off']
358         elif command.startswith('ADD '):
359             tokens = command.split(' ', 2)
360             if len(tokens) != 3:
361                 return ['wrong syntax, see HELP']
362             length = tokens[1].split(':')
363             if len(length) != 2:
364                 return ['wrong syntax, see HELP']
365             try:
366                 minutes = int(length[0])
367                 seconds = int(length[1])
368             except ValueError:
369                 return ['wrong syntax, see HELP']
370             self.playlist += [(tokens[2], minutes * 60 + seconds)]
371             self.game.changed = True
372             return ['added']
373         else:
374             return ['cannot understand command']
375
376
377
378 class Thing_BottleDeposit(Thing):
379     bottle_counter = 0
380     symbol_hint = 'O'
381
382     def proceed(self):
383         if self.bottle_counter >= 3:
384             self.bottle_counter = 0
385             choice = random.choice(['MusicPlayer', 'Hat'])
386             self.game.add_thing(choice, self.position)
387             msg = 'here is a gift as a reward for ecological consciousness –'
388             if choice == 'MusicPlayer':
389                 msg += 'pick it up and then use "command thing" on it!'
390             elif choice == 'Hat':
391                 msg += 'pick it up and then use "(un-)wear" on it!'
392             self.sound('BOTTLE DEPOSITOR', msg)
393
394     def accept(self):
395         self.bottle_counter += 1
396         self.sound('BOTTLE DEPOSITOR',
397                    'thanks for this empty bottle – deposit %s more for a gift!' %
398                    (3 - self.bottle_counter))
399
400
401
402 class Thing_Cookie(Thing):
403     symbol_hint = 'c'
404     portable = True
405
406     def __init__(self, *args, **kwargs):
407         import string
408         super().__init__(*args, **kwargs)
409         legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
410         self.thing_char = random.choice(list(legal_chars))
411
412
413
414 class Thing_CookieSpawner(Thing):
415     symbol_hint = 'O'
416
417     def accept(self, thing):
418         self.sound('OVEN', '*heat* *brrzt* here\'s a cookie!')
419         self.game.add_thing('Cookie', self.position)
420
421
422
423 class ThingAnimate(Thing):
424     blocks_movement = True
425     drunk = 0
426     tripping = 0
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
565     def __init__(self, *args, **kwargs):
566         super().__init__(*args, **kwargs)
567         self.carrying = None
568
569     def proceed(self):
570         super().proceed()
571         self.drunk -= 1
572         if self.drunk == 0:
573             self.send_msg('CHAT "You sober up."')
574             self.invalidate('fov')
575             self.game.changed = True
576         self.tripping -= 1
577         if self.tripping == 0:
578             self.send_msg('DEFAULT_COLORS')
579             self.send_msg('CHAT "You sober up."')
580             self.game.changed = True
581         elif self.tripping > 0 and self.tripping % 250 == 0:
582             self.send_msg('RANDOM_COLORS')
583             self.game.changed = True
584
585     def send_msg(self, msg):
586         for c_id in self.game.sessions:
587             if self.game.sessions[c_id]['thing_id'] == self.id_:
588                 self.game.io.send(msg, c_id)
589                 break
590
591     def uncarry(self):
592         t = self.carrying
593         t.carried = False
594         self.carrying = None
595         return t
596
597     def add_cookie_char(self, c):
598         if not self.name in self.game.players_hat_chars:
599             self.game.players_hat_chars[self.name] = ' #'  # default
600         if not c in self.game.players_hat_chars[self.name]:
601             self.game.players_hat_chars[self.name] += c
602
603     def get_cookie_chars(self):
604         if self.name in self.game.players_hat_chars:
605             return self.game.players_hat_chars[self.name]
606         return ' #'  # default