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):
153 def __init__(self, *args, **kwargs):
154 super().__init__(*args, **kwargs)
155 self.created_at = datetime.datetime.now()
159 if self.temporary and datetime.datetime.now() >\
160 self.created_at + datetime.timedelta(minutes=10):
161 self.game.remove_thing(self)
165 class ThingInstallable(Thing):
170 self.portable = False
177 class Thing_SignSpawner(ThingSpawner):
182 class Thing_Sign(ThingInstallable):
184 design_size = YX(16, 36)
186 def __init__(self, *args, **kwargs):
187 super().__init__(*args, **kwargs)
188 self.design = 'x' * self.design_size.y * self.design_size.x
192 class Thing_DoorSpawner(ThingSpawner):
196 door = super().proceed()
198 key = self.game.add_thing('DoorKey', self.position)
203 class Thing_DoorKey(Thing):
210 class Thing_Door(ThingInstallable):
212 blocks_movement = False
216 self.blocks_movement = False
217 self.blocks_light = False
218 self.blocks_sound = False
223 self.blocks_movement = True
224 self.blocks_light = True
225 self.blocks_sound = True
226 self.thing_char = '#'
230 self.thing_char = 'L'
234 class Thing_Psychedelic(Thing):
242 class Thing_PsychedelicSpawner(ThingSpawner):
244 child_type = 'Psychedelic'
248 class Thing_Bottle(Thing):
258 self.thing_char = '_'
262 all_players = [t for t in self.game.things if t.type_ == 'Player']
263 # TODO: refactor with ThingPlayer.prepare_multiprocessible_fov_stencil
264 # and ThingPlayer.fov_test
266 light_blockers = self.game.get_light_blockers()
267 obstacles = [t.position for t in self.game.things if t.blocks_light]
268 fov = FovMap(light_blockers, obstacles, self.game.maps,
269 self.position, fov_radius, self.game.get_map)
272 for p in all_players:
273 test_position = fov.target_yx(p.position[0], p.position[1])
274 if fov.inside(test_position) and fov[test_position] == '.':
275 visible_players += [p]
276 if len(visible_players) == 0:
277 self.sound('BOTTLE', 'no visible players in spin range')
278 pick = random.choice(visible_players)
279 self.sound('BOTTLE', 'BOTTLE picks: ' + pick.name)
283 class Thing_BottleSpawner(ThingSpawner):
284 child_type = 'Bottle'
288 class Thing_Hat(Thing):
291 design = ' +--+ ' + ' | | ' + '======'
294 design_size = YX(3, 6)
298 new_design += self.design[12]
299 new_design += self.design[13]
300 new_design += self.design[6]
301 new_design += self.design[7]
302 new_design += self.design[0]
303 new_design += self.design[1]
304 new_design += self.design[14]
305 new_design += self.design[15]
306 new_design += self.design[8]
307 new_design += self.design[9]
308 new_design += self.design[2]
309 new_design += self.design[3]
310 new_design += self.design[16]
311 new_design += self.design[17]
312 new_design += self.design[10]
313 new_design += self.design[11]
314 new_design += self.design[4]
315 new_design += self.design[5]
316 self.design = ''.join(new_design)
320 class Thing_HatRemixer(Thing):
323 def accept(self, hat):
326 legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
328 new_design += random.choice(list(legal_chars))
329 hat.design = new_design
330 self.sound('HAT REMIXER', 'remixing a hat …')
331 self.game.changed = True
332 self.game.record_change(self.position, 'other')
337 class Thing_MusicPlayer(Thing):
342 next_song_start = datetime.datetime.now()
347 def __init__(self, *args, **kwargs):
348 super().__init__(*args, **kwargs)
349 self.next_song_start = datetime.datetime.now()
353 if (not self.playing) or len(self.playlist) == 0:
355 if datetime.datetime.now() > self.next_song_start:
356 self.playlist_index += 1
357 if self.playlist_index == len(self.playlist):
358 self.playlist_index = 0
362 song_data = self.playlist[self.playlist_index]
363 self.next_song_start = datetime.datetime.now() +\
364 datetime.timedelta(seconds=song_data[1])
365 self.sound('MUSICPLAYER', song_data[0])
366 self.game.changed = True
368 def interpret(self, command):
370 if command == 'HELP':
371 msg_lines += ['available commands:']
372 msg_lines += ['HELP – show this help']
373 msg_lines += ['ON/OFF – toggle playback on/off']
374 msg_lines += ['REWIND – return to start of playlist']
375 msg_lines += ['LIST – list programmed item, durations']
376 msg_lines += ['REMOVE – remove current item']
377 msg_lines += ['SKIP – to skip to next item']
378 msg_lines += ['REPEAT – toggle playlist repeat on/off']
379 msg_lines += ['ADD LENGTH ITEM – add ITEM to playlist, with LENGTH in format "minutes:seconds" (something like "0:47" or "11:02")']
381 elif command == 'LIST':
382 msg_lines += ['playlist:']
384 for entry in self.playlist:
385 minutes = entry[1] // 60
386 seconds = entry[1] % 60
388 seconds = '0%s' % seconds
389 selector = 'next:' if i == self.playlist_index else ' '
390 msg_lines += ['%s %s:%s – %s' % (selector, minutes, seconds, entry[0])]
393 elif command == 'ON/OFF':
394 self.playing = False if self.playing else True
395 self.game.changed = True
400 elif command == 'REMOVE':
401 if len(self.playlist) == 0:
402 return ['playlist already empty']
403 del self.playlist[max(0, self.playlist_index)]
404 self.playlist_index -= 1
405 if self.playlist_index < -1:
406 self.playlist_index = -1
407 self.game.changed = True
408 return ['removed song']
409 elif command == 'REWIND':
410 self.playlist_index = -1
411 self.next_song_start = datetime.datetime.now()
412 self.game.changed = True
413 return ['back at start of playlist']
414 elif command == 'SKIP':
415 self.next_song_start = datetime.datetime.now()
416 self.game.changed = True
418 elif command == 'REPEAT':
419 self.repeat = False if self.repeat else True
420 self.game.changed = True
422 return ['playlist repeat turned on']
424 return ['playlist repeat turned off']
425 elif command.startswith('ADD '):
426 tokens = command.split(' ', 2)
428 return ['wrong syntax, see HELP']
429 length = tokens[1].split(':')
431 return ['wrong syntax, see HELP']
433 minutes = int(length[0])
434 seconds = int(length[1])
436 return ['wrong syntax, see HELP']
437 self.playlist += [(tokens[2], minutes * 60 + seconds)]
438 self.game.changed = True
441 return ['cannot understand command']
445 class Thing_BottleDeposit(Thing):
450 if self.bottle_counter >= 3:
451 self.bottle_counter = 0
452 choice = random.choice(['MusicPlayer', 'Hat'])
453 self.game.add_thing(choice, self.position)
454 msg = 'here is a gift as a reward for ecological consciousness –'
455 if choice == 'MusicPlayer':
456 msg += 'pick it up and then use "command thing" on it!'
457 elif choice == 'Hat':
458 msg += 'pick it up and then use "(un-)wear" on it!'
459 self.sound('BOTTLE DEPOSITOR', msg)
462 self.bottle_counter += 1
463 self.sound('BOTTLE DEPOSITOR',
464 'thanks for this empty bottle – deposit %s more for a gift!' %
465 (3 - self.bottle_counter))
469 class Thing_Stimulant(Thing):
477 class Thing_StimulantSpawner(ThingSpawner):
479 child_type = 'Stimulant'
483 class Thing_Cookie(Thing):
488 def __init__(self, *args, **kwargs):
490 super().__init__(*args, **kwargs)
491 legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
492 self.thing_char = random.choice(list(legal_chars))
496 class Thing_CookieSpawner(Thing):
499 def accept(self, thing):
500 self.sound('OVEN', '*heat* *brrzt* here\'s a cookie!')
501 self.game.add_thing('Cookie', self.position)
505 class Thing_Crate(Thing):
509 def __init__(self, *args, **kwargs):
510 super().__init__(*args, **kwargs)
513 def accept(self, thing):
514 self.content += [thing]
516 def remove_from_crate(self, thing):
517 self.content.remove(thing)
521 class Thing_CrateSpawner(ThingSpawner):
527 class ThingAnimate(Thing):
530 def __init__(self, *args, **kwargs):
531 super().__init__(*args, **kwargs)
532 self.next_task = [None]
534 self.invalidate('fov')
535 self.invalidate('other') # currently redundant though
537 def invalidate(self, type_):
540 self._visible_terrain = None
541 self._visible_control = None
542 self.invalidate('other')
543 elif type_ == 'other':
544 self._seen_things = None
545 self._seen_annotation_positions = None
546 self._seen_portal_positions = None
548 def set_next_task(self, task_name, args=()):
549 task_class = self.game.tasks[task_name]
550 self.next_task = [task_class(self, args)]
552 def get_next_task(self):
553 if self.next_task[0]:
554 task = self.next_task[0]
555 self.next_task = [None]
557 task.todo += max(0, -self.energy * 10)
561 if self.task is None:
562 self.task = self.get_next_task()
566 except (PlayError, GameError) as e:
570 if self.task.todo <= 0:
572 self.game.changed = True
573 self.task = self.get_next_task()
575 def prepare_multiprocessible_fov_stencil(self):
576 fov_radius = 3 if self.drunk > 0 else 12
577 light_blockers = self.game.get_light_blockers()
578 obstacles = [t.position for t in self.game.things if t.blocks_light]
579 self._fov = FovMap(light_blockers, obstacles, self.game.maps,
580 self.position, fov_radius, self.game.get_map)
582 def multiprocessible_fov_stencil(self):
583 self._fov.init_terrain()
586 def fov_stencil(self):
589 # due to the pre-multiprocessing in game.send_gamestate,
590 # the following should actually never be called
591 self.prepare_multiprocessible_fov_stencil()
592 self.multiprocessible_fov_stencil()
595 def fov_test(self, big_yx, little_yx):
596 test_position = self.fov_stencil.target_yx(big_yx, little_yx)
597 if self.fov_stencil.inside(test_position):
598 if self.fov_stencil[test_position] == '.':
602 def fov_stencil_map(self, map_type):
604 for yx in self.fov_stencil:
605 if self.fov_stencil[yx] == '.':
606 big_yx, little_yx = self.fov_stencil.source_yxyx(yx)
607 map_ = self.game.get_map(big_yx, map_type)
608 visible_terrain += map_[little_yx]
610 visible_terrain += ' '
611 return visible_terrain
614 def visible_terrain(self):
615 if self._visible_terrain:
616 return self._visible_terrain
617 self._visible_terrain = self.fov_stencil_map('normal')
618 return self._visible_terrain
621 def visible_control(self):
622 if self._visible_control:
623 return self._visible_control
624 self._visible_control = self.fov_stencil_map('control')
625 return self._visible_control
628 def seen_things(self):
629 if self._seen_things is not None:
630 return self._seen_things
631 self._seen_things = [t for t in self.game.things
632 if self.fov_test(*t.position)]
633 return self._seen_things
636 def seen_annotation_positions(self):
637 if self._seen_annotation_positions is not None:
638 return self._seen_annotation_positions
639 self._seen_annotation_positions = []
640 for big_yx in self.game.annotations:
641 for little_yx in [little_yx for little_yx
642 in self.game.annotations[big_yx]
643 if self.fov_test(big_yx, little_yx)]:
644 self._seen_annotation_positions += [(big_yx, little_yx)]
645 return self._seen_annotation_positions
648 def seen_portal_positions(self):
649 if self._seen_portal_positions is not None:
650 return self._seen_portal_positions
651 self._seen_portal_positions = []
652 for big_yx in self.game.portals:
653 for little_yx in [little_yx for little_yx
654 in self.game.portals[big_yx]
655 if self.fov_test(big_yx, little_yx)]:
656 self._seen_portal_positions += [(big_yx, little_yx)]
657 return self._seen_portal_positions
661 class Thing_Player(ThingAnimate):
669 def __init__(self, *args, **kwargs):
670 super().__init__(*args, **kwargs)
677 if self.tripping >= 0:
679 if self.need_for_toilet > 0:
680 terrain = self.game.maps[self.position[0]][self.position[1]]
681 if terrain in self.game.terrains:
682 terrain_type = self.game.terrains[terrain]
683 if 'toilet' in terrain_type.tags:
684 self.send_msg('CHAT "You use the toilet. What a relief!"')
685 self.need_for_toilet = 0
686 if self.need_for_toilet > 0:
687 if random.random() > 0.9999:
688 self.need_for_toilet += 1
689 self.game.changed = True
690 if 100000 * random.random() < self.need_for_toilet:
691 self.send_msg('CHAT "You need to go to a toilet."')
692 if self.need_for_toilet > 100:
693 self.send_msg('CHAT "You pee into your pants. Eww!"')
694 self.need_for_toilet = 0
695 self.game.changed = True
697 self.send_msg('CHAT "You sober up."')
698 self.invalidate('fov')
699 self.game.changed = True
700 if self.tripping == 0:
701 self.send_msg('DEFAULT_COLORS')
702 self.send_msg('CHAT "You sober up."')
703 self.game.changed = True
704 elif self.tripping > 0 and self.tripping % 250 == 0:
705 self.send_msg('RANDOM_COLORS')
706 self.game.changed = True
707 if random.random() > 0.9999:
712 if self.energy < 0 and self.standing and self.energy % 5 == 0:
713 self.send_msg('CHAT "All that walking or standing uses up '
714 'your energy, which makes you slower. Find a'
715 ' place to sit or lie down to regain it."')
716 self.game.changed = True
717 if self.dancing and random.random() > 0.99 and not self.next_task[0]:
719 direction = random.choice(self.game.map_geometry.directions)
720 self.set_next_task('MOVE', [direction])
721 if random.random() > 0.9:
723 self.game.changed = True
724 if 1000000 * random.random() < self.energy - 50:
725 self.send_msg('CHAT "Your body tries to '
726 'dance off its energy surplus."')
728 self.game.changed = True
730 def send_msg(self, msg):
731 for c_id in self.game.sessions:
732 if self.game.sessions[c_id]['thing_id'] == self.id_:
733 self.game.io.send(msg, c_id)
742 def add_cookie_char(self, c):
743 if not self.name in self.game.players_hat_chars:
744 self.game.players_hat_chars[self.name] = ' #' # default
745 if not c in self.game.players_hat_chars[self.name]:
746 self.game.players_hat_chars[self.name] += c
748 def get_cookie_chars(self):
749 chars = ' #' # default
750 if self.name in self.game.players_hat_chars:
751 chars = self.game.players_hat_chars[self.name]
752 chars_split = list(chars)
754 return ''.join(chars_split)