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
32 def __init__(self, *args, **kwargs):
33 super().__init__(*args, **kwargs)
40 return self.__class__.get_type()
44 return cls.__name__[len('Thing_'):]
46 def sound(self, name, msg):
47 from plomrogue.mapping import DijkstraMap
50 def lower_msg_by_volume(msg, volume, largest_audible_distance,
52 factor = largest_audible_distance / 4
59 in_url = False if in_url else True
61 while random.random() > volume * factor:
64 elif c != '.' and c != ' ':
72 largest_audible_distance = 20
73 obstacles = [t.position for t in self.game.things if t.blocks_sound]
74 targets = [t.position for t in self.game.things if t.type_ == 'Player']
75 sound_blockers = self.game.get_sound_blockers()
76 dijkstra_map = DijkstraMap(targets, sound_blockers, obstacles,
77 self.game.maps, self.position,
78 largest_audible_distance, self.game.get_map)
80 for m in re.finditer('https?://[^\s]+', msg):
81 url_limits += [m.start(), m.end()]
82 for c_id in self.game.sessions:
83 listener = self.game.get_player(c_id)
84 target_yx = dijkstra_map.target_yx(*listener.position, True)
87 listener_distance = dijkstra_map[target_yx]
88 if listener_distance > largest_audible_distance:
90 volume = 1 / max(1, listener_distance)
91 lowered_msg = lower_msg_by_volume(msg, volume,
92 largest_audible_distance,
94 lowered_nick = lower_msg_by_volume(name, volume,
95 largest_audible_distance)
97 # if listener.fov_test(self.position[0], self.position[1]):
98 # TODO: We might want to only show chat faces of players that are
99 # in the listener's FOV. However, if we do a fov_test here,
100 # this might set up a listener._fov where previously there was None,
101 # with ._fov = None serving to Game.send_gamestate() as an indicator
102 # that map view data for listener might be subject to change and
103 # therefore needs to be re-sent. If we generate an un-set ._fov
104 # here, this inhibits send_gamestate() from sending new map view
105 # data to listener. We need to re-structure this whole process
106 # if we want to use a FOV test on listener here.
107 if listener_distance < largest_audible_distance / 2:
108 self.game.io.send('CHATFACE %s' % self.id_, c_id)
109 if self.type_ == 'Player' and hasattr(self, 'thing_char'):
110 symbol = '/@' + self.thing_char
111 self.game.io.send('CHAT ' +
112 quote('vol:%.f%s %s%s: %s' % (volume * 100, '%',
113 lowered_nick, symbol,
119 class Thing_Item(Thing):
125 class ThingSpawner(Thing):
129 for t in [t for t in self.game.things
130 if t != self and t.position == self.position]:
132 return self.game.add_thing(self.child_type, self.position)
136 class Thing_ItemSpawner(ThingSpawner):
141 class Thing_SpawnPointSpawner(ThingSpawner):
142 child_type = 'SpawnPoint'
146 class Thing_SpawnPoint(Thing):
153 class ThingInstallable(Thing):
158 self.portable = False
165 class Thing_DoorSpawner(ThingSpawner):
169 door = super().proceed()
171 key = self.game.add_thing('DoorKey', self.position)
176 class Thing_DoorKey(Thing):
183 class Thing_Door(ThingInstallable):
185 blocks_movement = False
189 self.blocks_movement = False
190 self.blocks_light = False
191 self.blocks_sound = False
196 self.blocks_movement = True
197 self.blocks_light = True
198 self.blocks_sound = True
199 self.thing_char = '#'
203 self.thing_char = 'L'
207 class Thing_Psychedelic(Thing):
214 class Thing_PsychedelicSpawner(ThingSpawner):
216 child_type = 'Psychedelic'
220 class Thing_Bottle(Thing):
229 self.thing_char = '_'
233 all_players = [t for t in self.game.things if t.type_ == 'Player']
234 # TODO: refactor with ThingPlayer.prepare_multiprocessible_fov_stencil
235 # and ThingPlayer.fov_test
237 light_blockers = self.game.get_light_blockers()
238 obstacles = [t.position for t in self.game.things if t.blocks_light]
239 fov = FovMap(light_blockers, obstacles, self.game.maps,
240 self.position, fov_radius, self.game.get_map)
243 for p in all_players:
244 test_position = fov.target_yx(p.position[0], p.position[1])
245 if fov.inside(test_position) and fov[test_position] == '.':
246 visible_players += [p]
247 if len(visible_players) == 0:
248 self.sound('BOTTLE', 'no visible players in spin range')
249 pick = random.choice(visible_players)
250 self.sound('BOTTLE', 'BOTTLE picks: ' + pick.name)
254 class Thing_BottleSpawner(ThingSpawner):
255 child_type = 'Bottle'
259 class Thing_Hat(Thing):
262 design = ' +--+ ' + ' | | ' + '======'
268 new_design += self.design[12]
269 new_design += self.design[13]
270 new_design += self.design[6]
271 new_design += self.design[7]
272 new_design += self.design[0]
273 new_design += self.design[1]
274 new_design += self.design[14]
275 new_design += self.design[15]
276 new_design += self.design[8]
277 new_design += self.design[9]
278 new_design += self.design[2]
279 new_design += self.design[3]
280 new_design += self.design[16]
281 new_design += self.design[17]
282 new_design += self.design[10]
283 new_design += self.design[11]
284 new_design += self.design[4]
285 new_design += self.design[5]
286 self.design = ''.join(new_design)
290 class Thing_HatRemixer(Thing):
293 def accept(self, hat):
296 legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
298 new_design += random.choice(list(legal_chars))
299 hat.design = new_design
300 self.sound('HAT REMIXER', 'remixing a hat …')
301 self.game.changed = True
302 self.game.record_change(self.position, 'other')
307 class Thing_MusicPlayer(Thing):
312 next_song_start = datetime.datetime.now()
317 def __init__(self, *args, **kwargs):
318 super().__init__(*args, **kwargs)
319 self.next_song_start = datetime.datetime.now()
323 if (not self.playing) or len(self.playlist) == 0:
325 if datetime.datetime.now() > self.next_song_start:
326 self.playlist_index += 1
327 if self.playlist_index == len(self.playlist):
328 self.playlist_index = 0
332 song_data = self.playlist[self.playlist_index]
333 self.next_song_start = datetime.datetime.now() +\
334 datetime.timedelta(seconds=song_data[1])
335 self.sound('MUSICPLAYER', song_data[0])
336 self.game.changed = True
338 def interpret(self, command):
340 if command == 'HELP':
341 msg_lines += ['available commands:']
342 msg_lines += ['HELP – show this help']
343 msg_lines += ['ON/OFF – toggle playback on/off']
344 msg_lines += ['REWIND – return to start of playlist']
345 msg_lines += ['LIST – list programmed songs, durations']
346 msg_lines += ['SKIP – to skip to next song']
347 msg_lines += ['REPEAT – toggle playlist repeat on/off']
348 msg_lines += ['ADD LENGTH SONG – add SONG to playlist, with LENGTH in format "minutes:seconds", i.e. something like "0:47" or "11:02"']
350 elif command == 'LIST':
351 msg_lines += ['playlist:']
353 for entry in self.playlist:
354 minutes = entry[1] // 60
355 seconds = entry[1] % 60
357 seconds = '0%s' % seconds
358 selector = 'next:' if i == self.playlist_index else ' '
359 msg_lines += ['%s %s:%s – %s' % (selector, minutes, seconds, entry[0])]
362 elif command == 'ON/OFF':
363 self.playing = False if self.playing else True
364 self.game.changed = True
369 elif command == 'REMOVE':
370 if len(self.playlist) == 0:
371 return ['playlist already empty']
372 del self.playlist[max(0, self.playlist_index)]
373 self.playlist_index -= 1
374 if self.playlist_index < -1:
375 self.playlist_index = -1
376 self.game.changed = True
377 return ['removed song']
378 elif command == 'REWIND':
379 self.playlist_index = -1
380 self.next_song_start = datetime.datetime.now()
381 self.game.changed = True
382 return ['back at start of playlist']
383 elif command == 'SKIP':
384 self.next_song_start = datetime.datetime.now()
385 self.game.changed = True
387 elif command == 'REPEAT':
388 self.repeat = False if self.repeat else True
389 self.game.changed = True
391 return ['playlist repeat turned on']
393 return ['playlist repeat turned off']
394 elif command.startswith('ADD '):
395 tokens = command.split(' ', 2)
397 return ['wrong syntax, see HELP']
398 length = tokens[1].split(':')
400 return ['wrong syntax, see HELP']
402 minutes = int(length[0])
403 seconds = int(length[1])
405 return ['wrong syntax, see HELP']
406 self.playlist += [(tokens[2], minutes * 60 + seconds)]
407 self.game.changed = True
410 return ['cannot understand command']
414 class Thing_BottleDeposit(Thing):
419 if self.bottle_counter >= 3:
420 self.bottle_counter = 0
421 choice = random.choice(['MusicPlayer', 'Hat'])
422 self.game.add_thing(choice, self.position)
423 msg = 'here is a gift as a reward for ecological consciousness –'
424 if choice == 'MusicPlayer':
425 msg += 'pick it up and then use "command thing" on it!'
426 elif choice == 'Hat':
427 msg += 'pick it up and then use "(un-)wear" on it!'
428 self.sound('BOTTLE DEPOSITOR', msg)
431 self.bottle_counter += 1
432 self.sound('BOTTLE DEPOSITOR',
433 'thanks for this empty bottle – deposit %s more for a gift!' %
434 (3 - self.bottle_counter))
438 class Thing_Cookie(Thing):
442 def __init__(self, *args, **kwargs):
444 super().__init__(*args, **kwargs)
445 legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
446 self.thing_char = random.choice(list(legal_chars))
450 class Thing_CookieSpawner(Thing):
453 def accept(self, thing):
454 self.sound('OVEN', '*heat* *brrzt* here\'s a cookie!')
455 self.game.add_thing('Cookie', self.position)
459 class Thing_Crate(Thing):
463 def __init__(self, *args, **kwargs):
464 super().__init__(*args, **kwargs)
467 def accept(self, thing):
468 self.content += [thing]
470 def remove_from_crate(self, thing):
471 self.content.remove(thing)
475 class Thing_CrateSpawner(ThingSpawner):
481 class ThingAnimate(Thing):
484 def __init__(self, *args, **kwargs):
485 super().__init__(*args, **kwargs)
486 self.next_task = [None]
488 self.invalidate('fov')
489 self.invalidate('other') # currently redundant though
491 def invalidate(self, type_):
494 self._visible_terrain = None
495 self._visible_control = None
496 self.invalidate('other')
497 elif type_ == 'other':
498 self._seen_things = None
499 self._seen_annotation_positions = None
500 self._seen_portal_positions = None
502 def set_next_task(self, task_name, args=()):
503 task_class = self.game.tasks[task_name]
504 self.next_task = [task_class(self, args)]
506 def get_next_task(self):
507 if self.next_task[0]:
508 task = self.next_task[0]
509 self.next_task = [None]
511 task.todo += self.weariness * 10
515 if self.task is None:
516 self.task = self.get_next_task()
520 except (PlayError, GameError) as e:
524 if self.task.todo <= 0:
526 self.game.changed = True
527 self.task = self.get_next_task()
529 def prepare_multiprocessible_fov_stencil(self):
530 fov_radius = 3 if self.drunk > 0 else 12
531 light_blockers = self.game.get_light_blockers()
532 obstacles = [t.position for t in self.game.things if t.blocks_light]
533 self._fov = FovMap(light_blockers, obstacles, self.game.maps,
534 self.position, fov_radius, self.game.get_map)
536 def multiprocessible_fov_stencil(self):
537 self._fov.init_terrain()
540 def fov_stencil(self):
543 # due to the pre-multiprocessing in game.send_gamestate,
544 # the following should actually never be called
545 self.prepare_multiprocessible_fov_stencil()
546 self.multiprocessible_fov_stencil()
549 def fov_test(self, big_yx, little_yx):
550 test_position = self.fov_stencil.target_yx(big_yx, little_yx)
551 if self.fov_stencil.inside(test_position):
552 if self.fov_stencil[test_position] == '.':
556 def fov_stencil_map(self, map_type):
558 for yx in self.fov_stencil:
559 if self.fov_stencil[yx] == '.':
560 big_yx, little_yx = self.fov_stencil.source_yxyx(yx)
561 map_ = self.game.get_map(big_yx, map_type)
562 visible_terrain += map_[little_yx]
564 visible_terrain += ' '
565 return visible_terrain
568 def visible_terrain(self):
569 if self._visible_terrain:
570 return self._visible_terrain
571 self._visible_terrain = self.fov_stencil_map('normal')
572 return self._visible_terrain
575 def visible_control(self):
576 if self._visible_control:
577 return self._visible_control
578 self._visible_control = self.fov_stencil_map('control')
579 return self._visible_control
582 def seen_things(self):
583 if self._seen_things is not None:
584 return self._seen_things
585 self._seen_things = [t for t in self.game.things
586 if self.fov_test(*t.position)]
587 return self._seen_things
590 def seen_annotation_positions(self):
591 if self._seen_annotation_positions is not None:
592 return self._seen_annotation_positions
593 self._seen_annotation_positions = []
594 for big_yx in self.game.annotations:
595 for little_yx in [little_yx for little_yx
596 in self.game.annotations[big_yx]
597 if self.fov_test(big_yx, little_yx)]:
598 self._seen_annotation_positions += [(big_yx, little_yx)]
599 return self._seen_annotation_positions
602 def seen_portal_positions(self):
603 if self._seen_portal_positions is not None:
604 return self._seen_portal_positions
605 self._seen_portal_positions = []
606 for big_yx in self.game.portals:
607 for little_yx in [little_yx for little_yx
608 in self.game.portals[big_yx]
609 if self.fov_test(big_yx, little_yx)]:
610 self._seen_portal_positions += [(big_yx, little_yx)]
611 return self._seen_portal_positions
615 class Thing_Player(ThingAnimate):
622 def __init__(self, *args, **kwargs):
623 super().__init__(*args, **kwargs)
630 if self.tripping >= 0:
632 if self.need_for_toilet > 0:
633 terrain = self.game.maps[self.position[0]][self.position[1]]
634 if terrain in self.game.terrains:
635 terrain_type = self.game.terrains[terrain]
636 if 'toilet' in terrain_type.tags:
637 self.send_msg('CHAT "You use the toilet. What a relief!"')
638 self.need_for_toilet = 0
639 if self.need_for_toilet > 0:
640 if random.random() > 0.9999:
641 self.need_for_toilet += 1
642 self.game.changed = True
643 if 100000 * random.random() < self.need_for_toilet:
644 self.send_msg('CHAT "You need to go to a toilet."')
645 if self.need_for_toilet > 100:
646 self.send_msg('CHAT "You pee into your pants. Eww!"')
647 self.need_for_toilet = 0
648 self.game.changed = True
650 self.send_msg('CHAT "You sober up."')
651 self.invalidate('fov')
652 self.game.changed = True
653 if self.tripping == 0:
654 self.send_msg('DEFAULT_COLORS')
655 self.send_msg('CHAT "You sober up."')
656 self.game.changed = True
657 elif self.tripping > 0 and self.tripping % 250 == 0:
658 self.send_msg('RANDOM_COLORS')
659 self.game.changed = True
660 if random.random() > 0.9999:
663 if self.weariness % 5 == 0:
664 self.send_msg('CHAT "All that walking or standing makes '
665 'you weary, and thereby slower. Find a place '
666 'to sit or lie down to regain energy."')
667 elif self.weariness > 0:
669 self.game.changed = True
671 def send_msg(self, msg):
672 for c_id in self.game.sessions:
673 if self.game.sessions[c_id]['thing_id'] == self.id_:
674 self.game.io.send(msg, c_id)
683 def add_cookie_char(self, c):
684 if not self.name in self.game.players_hat_chars:
685 self.game.players_hat_chars[self.name] = ' #' # default
686 if not c in self.game.players_hat_chars[self.name]:
687 self.game.players_hat_chars[self.name] += c
689 def get_cookie_chars(self):
690 chars = ' #' # default
691 if self.name in self.game.players_hat_chars:
692 chars = self.game.players_hat_chars[self.name]
693 chars_split = list(chars)
695 return ''.join(chars_split)