home · contact · privacy
Re-factor treatment of things as obstacles for SourcedMaps.
[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     blocking = False
24     portable = False
25     protection = '.'
26     commandable = False
27     carried = False
28
29     def __init__(self, *args, **kwargs):
30         super().__init__(*args, **kwargs)
31
32     def proceed(self):
33         pass
34
35     @property
36     def type_(self):
37         return self.__class__.get_type()
38
39     @classmethod
40     def get_type(cls):
41         return cls.__name__[len('Thing_'):]
42
43     def sound(self, name, msg):
44         from plomrogue.mapping import DijkstraMap
45         import re
46
47         def lower_msg_by_volume(msg, volume, largest_audible_distance,
48                                 url_limits = []):
49             import random
50             factor = largest_audible_distance / 4
51             lowered_msg = ''
52             in_url = False
53             i = 0
54             for c in msg:
55                 c = c
56                 if i in url_limits:
57                     in_url = False if in_url else True
58                 if not in_url:
59                     while random.random() > volume * factor:
60                         if c.isupper():
61                             c = c.lower()
62                         elif c != '.' and c != ' ':
63                             c = '.'
64                         else:
65                             c = ' '
66                 lowered_msg += c
67                 i += 1
68             return lowered_msg
69
70         largest_audible_distance = 20
71         # player's don't block sound
72         obstacles = [t.position for t in self.game.things
73                      if t.blocking and t.type_ != 'Player']
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     blocking = False
150     portable = True
151     installable = True
152
153     def open(self):
154         self.blocking = False
155         del self.thing_char
156
157     def close(self):
158         self.blocking = True
159         self.thing_char = '#'
160
161     def install(self):
162         self.portable = False
163
164     def uninstall(self):
165         self.portable = True
166
167
168
169 class Thing_Bottle(Thing):
170     symbol_hint = 'B'
171     portable = True
172     full = True
173     thing_char = '~'
174     spinnable = True
175
176     def empty(self):
177         self.thing_char = '_'
178         self.full = False
179
180     def spin(self):
181         import random
182         all_players = [t for t in self.game.things if t.type_ == 'Player']
183         # TODO: refactor with ThingPlayer.prepare_multiprocessible_fov_stencil
184         # and ThingPlayer.fov_test
185         fov_map_class = self.game.map_geometry.fov_map_class
186         fov_radius = 12
187         light_blockers = self.game.get_light_blockers()
188         obstacles = [t.position for t in self.game.things if t.blocking]
189         fov = fov_map_class(light_blockers, obstacles, self.game.maps,
190                             self.position, fov_radius, self.game.get_map)
191         fov.init_terrain()
192         visible_players = []
193         for p in all_players:
194             test_position = fov.target_yx(p.position[0], p.position[1])
195             if fov.inside(test_position) and fov[test_position] == '.':
196                 visible_players += [p]
197         if len(visible_players) == 0:
198             self.sound('BOTTLE', 'no visible players in spin range')
199         pick = random.choice(visible_players)
200         self.sound('BOTTLE', 'BOTTLE picks: ' + pick.name)
201
202
203
204 class Thing_BottleSpawner(ThingSpawner):
205     child_type = 'Bottle'
206
207
208
209 class Thing_Hat(Thing):
210     symbol_hint = 'H'
211     portable = True
212     design = ' +--+ ' + ' |  | ' + '======'
213     spinnable = True
214
215     def spin(self):
216         new_design = ''
217         new_design += self.design[12]
218         new_design += self.design[13]
219         new_design += self.design[6]
220         new_design += self.design[7]
221         new_design += self.design[0]
222         new_design += self.design[1]
223         new_design += self.design[14]
224         new_design += self.design[15]
225         new_design += self.design[8]
226         new_design += self.design[9]
227         new_design += self.design[2]
228         new_design += self.design[3]
229         new_design += self.design[16]
230         new_design += self.design[17]
231         new_design += self.design[10]
232         new_design += self.design[11]
233         new_design += self.design[4]
234         new_design += self.design[5]
235         self.design = ''.join(new_design)
236
237
238
239 class Thing_HatRemixer(Thing):
240     symbol_hint = 'H'
241
242     def accept(self, hat):
243         import string
244         new_design = ''
245         legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
246         for i in range(18):
247             new_design += random.choice(list(legal_chars))
248         hat.design = new_design
249         self.sound('HAT REMIXER', 'remixing a hat …')
250         self.game.changed = True
251         self.game.record_change(self.position, 'other')
252
253
254
255 import datetime
256 class Thing_MusicPlayer(Thing):
257     symbol_hint = 'R'
258     commandable = True
259     portable = True
260     repeat = True
261     next_song_start = datetime.datetime.now()
262     playlist_index = -1
263     playing = True
264
265     def __init__(self, *args, **kwargs):
266         super().__init__(*args, **kwargs)
267         self.next_song_start = datetime.datetime.now()
268         self.playlist = []
269
270     def proceed(self):
271         if (not self.playing) or len(self.playlist) == 0:
272             return
273         if datetime.datetime.now() > self.next_song_start:
274             self.playlist_index += 1
275             if self.playlist_index == len(self.playlist):
276                 self.playlist_index = 0
277                 if not self.repeat:
278                     self.playing = False
279                     return
280             song_data = self.playlist[self.playlist_index]
281             self.next_song_start = datetime.datetime.now() +\
282                 datetime.timedelta(seconds=song_data[1])
283             self.sound('MUSICPLAYER', song_data[0])
284             self.game.changed = True
285
286     def interpret(self, command):
287         msg_lines = []
288         if command == 'HELP':
289             msg_lines += ['available commands:']
290             msg_lines += ['HELP – show this help']
291             msg_lines += ['ON/OFF – toggle playback on/off']
292             msg_lines += ['REWIND – return to start of playlist']
293             msg_lines += ['LIST – list programmed songs, durations']
294             msg_lines += ['SKIP – to skip to next song']
295             msg_lines += ['REPEAT – toggle playlist repeat on/off']
296             msg_lines += ['ADD LENGTH SONG – add SONG to playlist, with LENGTH in format "minutes:seconds", i.e. something like "0:47" or "11:02"']
297             return msg_lines
298         elif command == 'LIST':
299             msg_lines += ['playlist:']
300             i = 0
301             for entry in self.playlist:
302                 minutes = entry[1] // 60
303                 seconds = entry[1] % 60
304                 if seconds < 10:
305                     seconds = '0%s' % seconds
306                 selector = 'next:' if i == self.playlist_index else '     '
307                 msg_lines += ['%s %s:%s – %s' % (selector, minutes, seconds, entry[0])]
308                 i += 1
309             return msg_lines
310         elif command == 'ON/OFF':
311             self.playing = False if self.playing else True
312             self.game.changed = True
313             if self.playing:
314                 return ['playing']
315             else:
316                 return ['paused']
317         elif command == 'REMOVE':
318             if len(self.playlist) == 0:
319                 return ['playlist already empty']
320             del self.playlist[max(0, self.playlist_index)]
321             self.playlist_index -= 1
322             if self.playlist_index < -1:
323                 self.playlist_index = -1
324             self.game.changed = True
325             return ['removed song']
326         elif command == 'REWIND':
327             self.playlist_index = -1
328             self.next_song_start = datetime.datetime.now()
329             self.game.changed = True
330             return ['back at start of playlist']
331         elif command == 'SKIP':
332             self.next_song_start = datetime.datetime.now()
333             self.game.changed = True
334             return ['skipped']
335         elif command == 'REPEAT':
336             self.repeat = False if self.repeat else True
337             self.game.changed = True
338             if self.repeat:
339                 return ['playlist repeat turned on']
340             else:
341                 return ['playlist repeat turned off']
342         elif command.startswith('ADD '):
343             tokens = command.split(' ', 2)
344             if len(tokens) != 3:
345                 return ['wrong syntax, see HELP']
346             length = tokens[1].split(':')
347             if len(length) != 2:
348                 return ['wrong syntax, see HELP']
349             try:
350                 minutes = int(length[0])
351                 seconds = int(length[1])
352             except ValueError:
353                 return ['wrong syntax, see HELP']
354             self.playlist += [(tokens[2], minutes * 60 + seconds)]
355             self.game.changed = True
356             return ['added']
357         else:
358             return ['cannot understand command']
359
360
361
362 class Thing_BottleDeposit(Thing):
363     bottle_counter = 0
364     symbol_hint = 'O'
365
366     def proceed(self):
367         if self.bottle_counter >= 3:
368             self.bottle_counter = 0
369             choice = random.choice(['MusicPlayer', 'Hat'])
370             self.game.add_thing(choice, self.position)
371             msg = 'here is a gift as a reward for ecological consciousness –'
372             if choice == 'MusicPlayer':
373                 msg += 'pick it up and then use "command thing" on it!'
374             elif choice == 'Hat':
375                 msg += 'pick it up and then use "(un-)wear" on it!'
376             self.sound('BOTTLE DEPOSITOR', msg)
377
378     def accept(self):
379         self.bottle_counter += 1
380         self.sound('BOTTLE DEPOSITOR',
381                    'thanks for this empty bottle – deposit %s more for a gift!' %
382                    (3 - self.bottle_counter))
383
384
385
386 class Thing_Cookie(Thing):
387     symbol_hint = 'c'
388     portable = True
389
390     def __init__(self, *args, **kwargs):
391         import string
392         super().__init__(*args, **kwargs)
393         legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
394         self.thing_char = random.choice(list(legal_chars))
395
396
397
398 class Thing_CookieSpawner(Thing):
399     symbol_hint = 'O'
400
401     def accept(self, thing):
402         self.sound('OVEN', '*heat* *brrzt* here\'s a cookie!')
403         self.game.add_thing('Cookie', self.position)
404
405
406
407 class ThingAnimate(Thing):
408     blocking = True
409     drunk = 0
410
411     def __init__(self, *args, **kwargs):
412         super().__init__(*args, **kwargs)
413         self.next_task = [None]
414         self.task = None
415         self.invalidate('fov')
416         self.invalidate('other')  # currently redundant though
417
418     def invalidate(self, type_):
419         if type_ == 'fov':
420             self._fov = None
421             self._visible_terrain = None
422             self._visible_control = None
423             self.invalidate('other')
424         elif type_ == 'other':
425             self._seen_things = None
426             self._seen_annotation_positions = None
427             self._seen_portal_positions = None
428
429     def set_next_task(self, task_name, args=()):
430         task_class = self.game.tasks[task_name]
431         self.next_task = [task_class(self, args)]
432
433     def get_next_task(self):
434         if self.next_task[0]:
435             task = self.next_task[0]
436             self.next_task = [None]
437             task.check()
438             return task
439
440     def proceed(self):
441         self.drunk -= 1
442         if self.drunk == 0:
443             for c_id in self.game.sessions:
444                 if self.game.sessions[c_id]['thing_id'] == self.id_:
445                     # TODO: refactor with self.send_msg
446                     self.game.io.send('DEFAULT_COLORS', c_id)
447                     self.game.io.send('CHAT "You sober up."', c_id)
448                     self.invalidate('fov')
449                     break
450             self.game.changed = True
451         if self.task is None:
452             self.task = self.get_next_task()
453             return
454         try:
455             self.task.check()
456         except (PlayError, GameError) as e:
457             self.task = None
458             raise e
459         self.task.todo -= 1
460         if self.task.todo <= 0:
461             self.task.do()
462             self.game.changed = True
463             self.task = self.get_next_task()
464
465     def prepare_multiprocessible_fov_stencil(self):
466         fov_map_class = self.game.map_geometry.fov_map_class
467         fov_radius = 3 if self.drunk > 0 else 12
468         light_blockers = self.game.get_light_blockers()
469         obstacles = [t.position for t in self.game.things if t.blocking]
470         self._fov = fov_map_class(light_blockers, obstacles, self.game.maps,
471                                   self.position, fov_radius, self.game.get_map)
472
473     def multiprocessible_fov_stencil(self):
474         self._fov.init_terrain()
475
476     @property
477     def fov_stencil(self):
478         if self._fov:
479             return self._fov
480         # due to the pre-multiprocessing in game.send_gamestate,
481         # the following should actually never be called
482         self.prepare_multiprocessible_fov_stencil()
483         self.multiprocessible_fov_stencil()
484         return self._fov
485
486     def fov_stencil_make(self):
487         self._fov.make()
488
489     def fov_test(self, big_yx, little_yx):
490         test_position = self.fov_stencil.target_yx(big_yx, little_yx)
491         if self.fov_stencil.inside(test_position):
492             if self.fov_stencil[test_position] == '.':
493                 return True
494         return False
495
496     def fov_stencil_map(self, map_type):
497         visible_terrain = ''
498         for yx in self.fov_stencil:
499             if self.fov_stencil[yx] == '.':
500                 big_yx, little_yx = self.fov_stencil.source_yxyx(yx)
501                 map_ = self.game.get_map(big_yx, map_type)
502                 visible_terrain += map_[little_yx]
503             else:
504                 visible_terrain += ' '
505         return visible_terrain
506
507     @property
508     def visible_terrain(self):
509         if self._visible_terrain:
510             return self._visible_terrain
511         self._visible_terrain = self.fov_stencil_map('normal')
512         return self._visible_terrain
513
514     @property
515     def visible_control(self):
516         if self._visible_control:
517             return self._visible_control
518         self._visible_control = self.fov_stencil_map('control')
519         return self._visible_control
520
521     @property
522     def seen_things(self):
523         if self._seen_things is not None:
524             return self._seen_things
525         self._seen_things = [t for t in self.game.things
526                              if self.fov_test(*t.position)]
527         return self._seen_things
528
529     @property
530     def seen_annotation_positions(self):
531         if self._seen_annotation_positions is not None:
532             return self._seen_annotation_positions
533         self._seen_annotation_positions = []
534         for big_yx in self.game.annotations:
535             for little_yx in [little_yx for little_yx
536                               in self.game.annotations[big_yx]
537                               if self.fov_test(big_yx, little_yx)]:
538                 self._seen_annotation_positions += [(big_yx, little_yx)]
539         return self._seen_annotation_positions
540
541     @property
542     def seen_portal_positions(self):
543         if self._seen_portal_positions is not None:
544             return self._seen_portal_positions
545         self._seen_portal_positions = []
546         for big_yx in self.game.portals:
547             for little_yx in [little_yx for little_yx
548                               in self.game.portals[big_yx]
549                               if self.fov_test(big_yx, little_yx)]:
550                 self._seen_portal_positions += [(big_yx, little_yx)]
551         return self._seen_portal_positions
552
553
554
555 class Thing_Player(ThingAnimate):
556     symbol_hint = '@'
557
558     def __init__(self, *args, **kwargs):
559         super().__init__(*args, **kwargs)
560         self.carrying = None
561
562     def send_msg(self, msg):
563         for c_id in self.game.sessions:
564             if self.game.sessions[c_id]['thing_id'] == self.id_:
565                 self.game.io.send(msg, c_id)
566                 break
567
568     def uncarry(self):
569         t = self.carrying
570         t.carried = False
571         self.carrying = None
572         return t
573
574     def add_cookie_char(self, c):
575         if not self.name in self.game.players_hat_chars:
576             self.game.players_hat_chars[self.name] = ' #'  # default
577         if not c in self.game.players_hat_chars[self.name]:
578             self.game.players_hat_chars[self.name] += c
579
580     def get_cookie_chars(self):
581         if self.name in self.game.players_hat_chars:
582             return self.game.players_hat_chars[self.name]
583         return ' #'  # default