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 ThingAnimate(Thing):
462 def __init__(self, *args, **kwargs):
463 super().__init__(*args, **kwargs)
464 self.next_task = [None]
466 self.invalidate('fov')
467 self.invalidate('other') # currently redundant though
469 def invalidate(self, type_):
472 self._visible_terrain = None
473 self._visible_control = None
474 self.invalidate('other')
475 elif type_ == 'other':
476 self._seen_things = None
477 self._seen_annotation_positions = None
478 self._seen_portal_positions = None
480 def set_next_task(self, task_name, args=()):
481 task_class = self.game.tasks[task_name]
482 self.next_task = [task_class(self, args)]
484 def get_next_task(self):
485 if self.next_task[0]:
486 task = self.next_task[0]
487 self.next_task = [None]
489 task.todo += self.weariness * 10
493 if self.task is None:
494 self.task = self.get_next_task()
498 except (PlayError, GameError) as e:
502 if self.task.todo <= 0:
504 self.game.changed = True
505 self.task = self.get_next_task()
507 def prepare_multiprocessible_fov_stencil(self):
508 fov_radius = 3 if self.drunk > 0 else 12
509 light_blockers = self.game.get_light_blockers()
510 obstacles = [t.position for t in self.game.things if t.blocks_light]
511 self._fov = FovMap(light_blockers, obstacles, self.game.maps,
512 self.position, fov_radius, self.game.get_map)
514 def multiprocessible_fov_stencil(self):
515 self._fov.init_terrain()
518 def fov_stencil(self):
521 # due to the pre-multiprocessing in game.send_gamestate,
522 # the following should actually never be called
523 self.prepare_multiprocessible_fov_stencil()
524 self.multiprocessible_fov_stencil()
527 def fov_test(self, big_yx, little_yx):
528 test_position = self.fov_stencil.target_yx(big_yx, little_yx)
529 if self.fov_stencil.inside(test_position):
530 if self.fov_stencil[test_position] == '.':
534 def fov_stencil_map(self, map_type):
536 for yx in self.fov_stencil:
537 if self.fov_stencil[yx] == '.':
538 big_yx, little_yx = self.fov_stencil.source_yxyx(yx)
539 map_ = self.game.get_map(big_yx, map_type)
540 visible_terrain += map_[little_yx]
542 visible_terrain += ' '
543 return visible_terrain
546 def visible_terrain(self):
547 if self._visible_terrain:
548 return self._visible_terrain
549 self._visible_terrain = self.fov_stencil_map('normal')
550 return self._visible_terrain
553 def visible_control(self):
554 if self._visible_control:
555 return self._visible_control
556 self._visible_control = self.fov_stencil_map('control')
557 return self._visible_control
560 def seen_things(self):
561 if self._seen_things is not None:
562 return self._seen_things
563 self._seen_things = [t for t in self.game.things
564 if self.fov_test(*t.position)]
565 return self._seen_things
568 def seen_annotation_positions(self):
569 if self._seen_annotation_positions is not None:
570 return self._seen_annotation_positions
571 self._seen_annotation_positions = []
572 for big_yx in self.game.annotations:
573 for little_yx in [little_yx for little_yx
574 in self.game.annotations[big_yx]
575 if self.fov_test(big_yx, little_yx)]:
576 self._seen_annotation_positions += [(big_yx, little_yx)]
577 return self._seen_annotation_positions
580 def seen_portal_positions(self):
581 if self._seen_portal_positions is not None:
582 return self._seen_portal_positions
583 self._seen_portal_positions = []
584 for big_yx in self.game.portals:
585 for little_yx in [little_yx for little_yx
586 in self.game.portals[big_yx]
587 if self.fov_test(big_yx, little_yx)]:
588 self._seen_portal_positions += [(big_yx, little_yx)]
589 return self._seen_portal_positions
593 class Thing_Player(ThingAnimate):
600 def __init__(self, *args, **kwargs):
601 super().__init__(*args, **kwargs)
608 if self.tripping >= 0:
610 if self.need_for_toilet > 0:
611 terrain = self.game.maps[self.position[0]][self.position[1]]
612 if terrain in self.game.terrains:
613 terrain_type = self.game.terrains[terrain]
614 if 'toilet' in terrain_type.tags:
615 self.send_msg('CHAT "You use the toilet. What a relief!"')
616 self.need_for_toilet = 0
617 if self.need_for_toilet > 0:
618 if random.random() > 0.9999:
619 self.need_for_toilet += 1
620 self.game.changed = True
621 if 100000 * random.random() < self.need_for_toilet:
622 self.send_msg('CHAT "You need to go to a toilet."')
623 if self.need_for_toilet > 100:
624 self.send_msg('CHAT "You pee into your pants. Eww!"')
625 self.need_for_toilet = 0
626 self.game.changed = True
628 self.send_msg('CHAT "You sober up."')
629 self.invalidate('fov')
630 self.game.changed = True
631 if self.tripping == 0:
632 self.send_msg('DEFAULT_COLORS')
633 self.send_msg('CHAT "You sober up."')
634 self.game.changed = True
635 elif self.tripping > 0 and self.tripping % 250 == 0:
636 self.send_msg('RANDOM_COLORS')
637 self.game.changed = True
638 if random.random() > 0.9999:
641 if self.weariness % 5 == 0:
642 self.send_msg('CHAT "All that walking or standing makes '
643 'you weary, and thereby slower. Find a place '
644 'to sit or lie down to regain energy."')
645 elif self.weariness > 0:
647 self.game.changed = True
649 def send_msg(self, msg):
650 for c_id in self.game.sessions:
651 if self.game.sessions[c_id]['thing_id'] == self.id_:
652 self.game.io.send(msg, c_id)
661 def add_cookie_char(self, c):
662 if not self.name in self.game.players_hat_chars:
663 self.game.players_hat_chars[self.name] = ' #' # default
664 if not c in self.game.players_hat_chars[self.name]:
665 self.game.players_hat_chars[self.name] += c
667 def get_cookie_chars(self):
668 chars = ' #' # default
669 if self.name in self.game.players_hat_chars:
670 chars = self.game.players_hat_chars[self.name]
671 chars_split = list(chars)
673 return ''.join(chars_split)