1 from plomrogue.errors import GameError, PlayError
2 from plomrogue.mapping import YX, FovMap
3 from plomrogue.misc import quote
12 def __init__(self, game, id_=0, position=(YX(0, 0), YX(0, 0))):
15 self.id_ = self.game.new_thing_id()
18 self.position = position
22 class Thing(ThingBase):
23 blocks_movement = False
33 def __init__(self, *args, **kwargs):
34 super().__init__(*args, **kwargs)
41 return self.__class__.get_type()
45 return cls.__name__[len('Thing_'):]
47 def sound(self, name, msg):
48 from plomrogue.mapping import DijkstraMap
51 def lower_msg_by_volume(msg, volume, largest_audible_distance,
53 factor = largest_audible_distance / 4
60 in_url = False if in_url else True
62 while random.random() > volume * factor:
65 elif c != '.' and c != ' ':
73 largest_audible_distance = 20
74 obstacles = [t.position for t in self.game.things if t.blocks_sound]
75 targets = [t.position for t in self.game.things if t.type_ == 'Player']
76 sound_blockers = self.game.get_sound_blockers()
77 dijkstra_map = DijkstraMap(targets, sound_blockers, obstacles,
78 self.game.maps, self.position,
79 largest_audible_distance, self.game.get_map)
81 for m in re.finditer('https?://[^\s]+', msg):
82 url_limits += [m.start(), m.end()]
83 for c_id in self.game.sessions:
84 listener = self.game.get_player(c_id)
85 target_yx = dijkstra_map.target_yx(*listener.position, True)
88 listener_distance = dijkstra_map[target_yx]
89 if listener_distance > largest_audible_distance:
91 volume = 1 / max(1, listener_distance)
92 lowered_msg = lower_msg_by_volume(msg, volume,
93 largest_audible_distance,
95 lowered_nick = lower_msg_by_volume(name, volume,
96 largest_audible_distance)
98 # if listener.fov_test(self.position[0], self.position[1]):
99 # TODO: We might want to only show chat faces of players that are
100 # in the listener's FOV. However, if we do a fov_test here,
101 # this might set up a listener._fov where previously there was None,
102 # with ._fov = None serving to Game.send_gamestate() as an indicator
103 # that map view data for listener might be subject to change and
104 # therefore needs to be re-sent. If we generate an un-set ._fov
105 # here, this inhibits send_gamestate() from sending new map view
106 # data to listener. We need to re-structure this whole process
107 # if we want to use a FOV test on listener here.
108 if listener_distance < largest_audible_distance / 2:
109 self.game.io.send('CHATFACE %s' % self.id_, c_id)
110 if self.type_ == 'Player' and hasattr(self, 'thing_char'):
111 symbol = '/@' + self.thing_char
112 self.game.io.send('CHAT ' +
113 quote('vol:%.f%s %s%s: %s' % (volume * 100, '%',
114 lowered_nick, symbol,
120 class Thing_Item(Thing):
126 class ThingSpawner(Thing):
130 for t in [t for t in self.game.things
131 if t != self and t.position == self.position]:
133 return self.game.add_thing(self.child_type, self.position)
137 class Thing_ItemSpawner(ThingSpawner):
142 class Thing_SpawnPointSpawner(ThingSpawner):
143 child_type = 'SpawnPoint'
147 class Thing_SpawnPoint(Thing):
154 class ThingInstallable(Thing):
159 self.portable = False
166 class Thing_DoorSpawner(ThingSpawner):
170 door = super().proceed()
172 key = self.game.add_thing('DoorKey', self.position)
177 class Thing_DoorKey(Thing):
184 class Thing_Door(ThingInstallable):
186 blocks_movement = False
190 self.blocks_movement = False
191 self.blocks_light = False
192 self.blocks_sound = False
197 self.blocks_movement = True
198 self.blocks_light = True
199 self.blocks_sound = True
200 self.thing_char = '#'
204 self.thing_char = 'L'
208 class Thing_Psychedelic(Thing):
216 class Thing_PsychedelicSpawner(ThingSpawner):
218 child_type = 'Psychedelic'
222 class Thing_Bottle(Thing):
232 self.thing_char = '_'
236 all_players = [t for t in self.game.things if t.type_ == 'Player']
237 # TODO: refactor with ThingPlayer.prepare_multiprocessible_fov_stencil
238 # and ThingPlayer.fov_test
240 light_blockers = self.game.get_light_blockers()
241 obstacles = [t.position for t in self.game.things if t.blocks_light]
242 fov = FovMap(light_blockers, obstacles, self.game.maps,
243 self.position, fov_radius, self.game.get_map)
246 for p in all_players:
247 test_position = fov.target_yx(p.position[0], p.position[1])
248 if fov.inside(test_position) and fov[test_position] == '.':
249 visible_players += [p]
250 if len(visible_players) == 0:
251 self.sound('BOTTLE', 'no visible players in spin range')
252 pick = random.choice(visible_players)
253 self.sound('BOTTLE', 'BOTTLE picks: ' + pick.name)
257 class Thing_BottleSpawner(ThingSpawner):
258 child_type = 'Bottle'
262 class Thing_Hat(Thing):
265 design = ' +--+ ' + ' | | ' + '======'
271 new_design += self.design[12]
272 new_design += self.design[13]
273 new_design += self.design[6]
274 new_design += self.design[7]
275 new_design += self.design[0]
276 new_design += self.design[1]
277 new_design += self.design[14]
278 new_design += self.design[15]
279 new_design += self.design[8]
280 new_design += self.design[9]
281 new_design += self.design[2]
282 new_design += self.design[3]
283 new_design += self.design[16]
284 new_design += self.design[17]
285 new_design += self.design[10]
286 new_design += self.design[11]
287 new_design += self.design[4]
288 new_design += self.design[5]
289 self.design = ''.join(new_design)
293 class Thing_HatRemixer(Thing):
296 def accept(self, hat):
299 legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
301 new_design += random.choice(list(legal_chars))
302 hat.design = new_design
303 self.sound('HAT REMIXER', 'remixing a hat …')
304 self.game.changed = True
305 self.game.record_change(self.position, 'other')
310 class Thing_MusicPlayer(Thing):
315 next_song_start = datetime.datetime.now()
320 def __init__(self, *args, **kwargs):
321 super().__init__(*args, **kwargs)
322 self.next_song_start = datetime.datetime.now()
326 if (not self.playing) or len(self.playlist) == 0:
328 if datetime.datetime.now() > self.next_song_start:
329 self.playlist_index += 1
330 if self.playlist_index == len(self.playlist):
331 self.playlist_index = 0
335 song_data = self.playlist[self.playlist_index]
336 self.next_song_start = datetime.datetime.now() +\
337 datetime.timedelta(seconds=song_data[1])
338 self.sound('MUSICPLAYER', song_data[0])
339 self.game.changed = True
341 def interpret(self, command):
343 if command == 'HELP':
344 msg_lines += ['available commands:']
345 msg_lines += ['HELP – show this help']
346 msg_lines += ['ON/OFF – toggle playback on/off']
347 msg_lines += ['REWIND – return to start of playlist']
348 msg_lines += ['LIST – list programmed songs, durations']
349 msg_lines += ['SKIP – to skip to next song']
350 msg_lines += ['REPEAT – toggle playlist repeat on/off']
351 msg_lines += ['ADD LENGTH SONG – add SONG to playlist, with LENGTH in format "minutes:seconds", i.e. something like "0:47" or "11:02"']
353 elif command == 'LIST':
354 msg_lines += ['playlist:']
356 for entry in self.playlist:
357 minutes = entry[1] // 60
358 seconds = entry[1] % 60
360 seconds = '0%s' % seconds
361 selector = 'next:' if i == self.playlist_index else ' '
362 msg_lines += ['%s %s:%s – %s' % (selector, minutes, seconds, entry[0])]
365 elif command == 'ON/OFF':
366 self.playing = False if self.playing else True
367 self.game.changed = True
372 elif command == 'REMOVE':
373 if len(self.playlist) == 0:
374 return ['playlist already empty']
375 del self.playlist[max(0, self.playlist_index)]
376 self.playlist_index -= 1
377 if self.playlist_index < -1:
378 self.playlist_index = -1
379 self.game.changed = True
380 return ['removed song']
381 elif command == 'REWIND':
382 self.playlist_index = -1
383 self.next_song_start = datetime.datetime.now()
384 self.game.changed = True
385 return ['back at start of playlist']
386 elif command == 'SKIP':
387 self.next_song_start = datetime.datetime.now()
388 self.game.changed = True
390 elif command == 'REPEAT':
391 self.repeat = False if self.repeat else True
392 self.game.changed = True
394 return ['playlist repeat turned on']
396 return ['playlist repeat turned off']
397 elif command.startswith('ADD '):
398 tokens = command.split(' ', 2)
400 return ['wrong syntax, see HELP']
401 length = tokens[1].split(':')
403 return ['wrong syntax, see HELP']
405 minutes = int(length[0])
406 seconds = int(length[1])
408 return ['wrong syntax, see HELP']
409 self.playlist += [(tokens[2], minutes * 60 + seconds)]
410 self.game.changed = True
413 return ['cannot understand command']
417 class Thing_BottleDeposit(Thing):
422 if self.bottle_counter >= 3:
423 self.bottle_counter = 0
424 choice = random.choice(['MusicPlayer', 'Hat'])
425 self.game.add_thing(choice, self.position)
426 msg = 'here is a gift as a reward for ecological consciousness –'
427 if choice == 'MusicPlayer':
428 msg += 'pick it up and then use "command thing" on it!'
429 elif choice == 'Hat':
430 msg += 'pick it up and then use "(un-)wear" on it!'
431 self.sound('BOTTLE DEPOSITOR', msg)
434 self.bottle_counter += 1
435 self.sound('BOTTLE DEPOSITOR',
436 'thanks for this empty bottle – deposit %s more for a gift!' %
437 (3 - self.bottle_counter))
441 class Thing_Stimulant(Thing):
449 class Thing_StimulantSpawner(ThingSpawner):
451 child_type = 'Stimulant'
455 class Thing_Cookie(Thing):
460 def __init__(self, *args, **kwargs):
462 super().__init__(*args, **kwargs)
463 legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
464 self.thing_char = random.choice(list(legal_chars))
468 class Thing_CookieSpawner(Thing):
471 def accept(self, thing):
472 self.sound('OVEN', '*heat* *brrzt* here\'s a cookie!')
473 self.game.add_thing('Cookie', self.position)
477 class Thing_Crate(Thing):
481 def __init__(self, *args, **kwargs):
482 super().__init__(*args, **kwargs)
485 def accept(self, thing):
486 self.content += [thing]
488 def remove_from_crate(self, thing):
489 self.content.remove(thing)
493 class Thing_CrateSpawner(ThingSpawner):
499 class ThingAnimate(Thing):
502 def __init__(self, *args, **kwargs):
503 super().__init__(*args, **kwargs)
504 self.next_task = [None]
506 self.invalidate('fov')
507 self.invalidate('other') # currently redundant though
509 def invalidate(self, type_):
512 self._visible_terrain = None
513 self._visible_control = None
514 self.invalidate('other')
515 elif type_ == 'other':
516 self._seen_things = None
517 self._seen_annotation_positions = None
518 self._seen_portal_positions = None
520 def set_next_task(self, task_name, args=()):
521 task_class = self.game.tasks[task_name]
522 self.next_task = [task_class(self, args)]
524 def get_next_task(self):
525 if self.next_task[0]:
526 task = self.next_task[0]
527 self.next_task = [None]
529 task.todo += max(0, -self.energy * 10)
533 if self.task is None:
534 self.task = self.get_next_task()
538 except (PlayError, GameError) as e:
542 if self.task.todo <= 0:
544 self.game.changed = True
545 self.task = self.get_next_task()
547 def prepare_multiprocessible_fov_stencil(self):
548 fov_radius = 3 if self.drunk > 0 else 12
549 light_blockers = self.game.get_light_blockers()
550 obstacles = [t.position for t in self.game.things if t.blocks_light]
551 self._fov = FovMap(light_blockers, obstacles, self.game.maps,
552 self.position, fov_radius, self.game.get_map)
554 def multiprocessible_fov_stencil(self):
555 self._fov.init_terrain()
558 def fov_stencil(self):
561 # due to the pre-multiprocessing in game.send_gamestate,
562 # the following should actually never be called
563 self.prepare_multiprocessible_fov_stencil()
564 self.multiprocessible_fov_stencil()
567 def fov_test(self, big_yx, little_yx):
568 test_position = self.fov_stencil.target_yx(big_yx, little_yx)
569 if self.fov_stencil.inside(test_position):
570 if self.fov_stencil[test_position] == '.':
574 def fov_stencil_map(self, map_type):
576 for yx in self.fov_stencil:
577 if self.fov_stencil[yx] == '.':
578 big_yx, little_yx = self.fov_stencil.source_yxyx(yx)
579 map_ = self.game.get_map(big_yx, map_type)
580 visible_terrain += map_[little_yx]
582 visible_terrain += ' '
583 return visible_terrain
586 def visible_terrain(self):
587 if self._visible_terrain:
588 return self._visible_terrain
589 self._visible_terrain = self.fov_stencil_map('normal')
590 return self._visible_terrain
593 def visible_control(self):
594 if self._visible_control:
595 return self._visible_control
596 self._visible_control = self.fov_stencil_map('control')
597 return self._visible_control
600 def seen_things(self):
601 if self._seen_things is not None:
602 return self._seen_things
603 self._seen_things = [t for t in self.game.things
604 if self.fov_test(*t.position)]
605 return self._seen_things
608 def seen_annotation_positions(self):
609 if self._seen_annotation_positions is not None:
610 return self._seen_annotation_positions
611 self._seen_annotation_positions = []
612 for big_yx in self.game.annotations:
613 for little_yx in [little_yx for little_yx
614 in self.game.annotations[big_yx]
615 if self.fov_test(big_yx, little_yx)]:
616 self._seen_annotation_positions += [(big_yx, little_yx)]
617 return self._seen_annotation_positions
620 def seen_portal_positions(self):
621 if self._seen_portal_positions is not None:
622 return self._seen_portal_positions
623 self._seen_portal_positions = []
624 for big_yx in self.game.portals:
625 for little_yx in [little_yx for little_yx
626 in self.game.portals[big_yx]
627 if self.fov_test(big_yx, little_yx)]:
628 self._seen_portal_positions += [(big_yx, little_yx)]
629 return self._seen_portal_positions
633 class Thing_Player(ThingAnimate):
641 def __init__(self, *args, **kwargs):
642 super().__init__(*args, **kwargs)
649 if self.tripping >= 0:
651 if self.need_for_toilet > 0:
652 terrain = self.game.maps[self.position[0]][self.position[1]]
653 if terrain in self.game.terrains:
654 terrain_type = self.game.terrains[terrain]
655 if 'toilet' in terrain_type.tags:
656 self.send_msg('CHAT "You use the toilet. What a relief!"')
657 self.need_for_toilet = 0
658 if self.need_for_toilet > 0:
659 if random.random() > 0.9999:
660 self.need_for_toilet += 1
661 self.game.changed = True
662 if 100000 * random.random() < self.need_for_toilet:
663 self.send_msg('CHAT "You need to go to a toilet."')
664 if self.need_for_toilet > 100:
665 self.send_msg('CHAT "You pee into your pants. Eww!"')
666 self.need_for_toilet = 0
667 self.game.changed = True
669 self.send_msg('CHAT "You sober up."')
670 self.invalidate('fov')
671 self.game.changed = True
672 if self.tripping == 0:
673 self.send_msg('DEFAULT_COLORS')
674 self.send_msg('CHAT "You sober up."')
675 self.game.changed = True
676 elif self.tripping > 0 and self.tripping % 250 == 0:
677 self.send_msg('RANDOM_COLORS')
678 self.game.changed = True
679 if random.random() > 0.9999:
684 if self.energy < 0 and self.standing and self.energy % 5 == 0:
685 self.send_msg('CHAT "All that walking or standing uses up '
686 'your energy, which makes you slower. Find a'
687 ' place to sit or lie down to regain it."')
688 self.game.changed = True
689 if self.dancing and random.random() > 0.99 and not self.next_task[0]:
691 direction = random.choice(self.game.map_geometry.directions)
692 self.set_next_task('MOVE', [direction])
693 if random.random() > 0.9:
695 self.game.changed = True
696 if 1000000 * random.random() < self.energy - 50:
697 self.send_msg('CHAT "Your body tries to '
698 'dance off its energy surplus."')
700 self.game.changed = True
702 def send_msg(self, msg):
703 for c_id in self.game.sessions:
704 if self.game.sessions[c_id]['thing_id'] == self.id_:
705 self.game.io.send(msg, c_id)
714 def add_cookie_char(self, c):
715 if not self.name in self.game.players_hat_chars:
716 self.game.players_hat_chars[self.name] = ' #' # default
717 if not c in self.game.players_hat_chars[self.name]:
718 self.game.players_hat_chars[self.name] += c
720 def get_cookie_chars(self):
721 chars = ' #' # default
722 if self.name in self.game.players_hat_chars:
723 chars = self.game.players_hat_chars[self.name]
724 chars_split = list(chars)
726 return ''.join(chars_split)