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
31 def __init__(self, *args, **kwargs):
32 super().__init__(*args, **kwargs)
39 return self.__class__.get_type()
43 return cls.__name__[len('Thing_'):]
45 def sound(self, name, msg):
46 from plomrogue.mapping import DijkstraMap
49 def lower_msg_by_volume(msg, volume, largest_audible_distance,
51 factor = largest_audible_distance / 4
58 in_url = False if in_url else True
60 while random.random() > volume * factor:
63 elif c != '.' and c != ' ':
71 largest_audible_distance = 20
72 obstacles = [t.position for t in self.game.things if t.blocks_sound]
73 targets = [t.position for t in self.game.things if t.type_ == 'Player']
74 sound_blockers = self.game.get_sound_blockers()
75 dijkstra_map = DijkstraMap(targets, sound_blockers, obstacles,
76 self.game.maps, self.position,
77 largest_audible_distance, self.game.get_map)
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)
86 listener_distance = dijkstra_map[target_yx]
87 if listener_distance > largest_audible_distance:
89 volume = 1 / max(1, listener_distance)
90 lowered_msg = lower_msg_by_volume(msg, volume,
91 largest_audible_distance,
93 lowered_nick = lower_msg_by_volume(name, volume,
94 largest_audible_distance)
96 # if listener.fov_test(self.position[0], self.position[1]):
97 # TODO: We might want to only show chat faces of players that are
98 # in the listener's FOV. However, if we do a fov_test here,
99 # this might set up a listener._fov where previously there was None,
100 # with ._fov = None serving to Game.send_gamestate() as an indicator
101 # that map view data for listener might be subject to change and
102 # therefore needs to be re-sent. If we generate an un-set ._fov
103 # here, this inhibits send_gamestate() from sending new map view
104 # data to listener. We need to re-structure this whole process
105 # if we want to use a FOV test on listener here.
106 if listener_distance < largest_audible_distance / 2:
107 self.game.io.send('CHATFACE %s' % self.id_, c_id)
108 if self.type_ == 'Player' and hasattr(self, 'thing_char'):
109 symbol = '/@' + self.thing_char
110 self.game.io.send('CHAT ' +
111 quote('vol:%.f%s %s%s: %s' % (volume * 100, '%',
112 lowered_nick, symbol,
118 class Thing_Item(Thing):
124 class ThingSpawner(Thing):
128 for t in [t for t in self.game.things
129 if t != self and t.position == self.position]:
131 return self.game.add_thing(self.child_type, self.position)
135 class Thing_ItemSpawner(ThingSpawner):
140 class Thing_SpawnPointSpawner(ThingSpawner):
141 child_type = 'SpawnPoint'
145 class Thing_SpawnPoint(Thing):
152 class ThingInstallable(Thing):
157 self.portable = False
164 class Thing_DoorSpawner(ThingSpawner):
168 door = super().proceed()
170 key = self.game.add_thing('DoorKey', self.position)
175 class Thing_DoorKey(Thing):
182 class Thing_Door(ThingInstallable):
184 blocks_movement = False
188 self.blocks_movement = False
189 self.blocks_light = False
190 self.blocks_sound = False
195 self.blocks_movement = True
196 self.blocks_light = True
197 self.blocks_sound = True
198 self.thing_char = '#'
202 self.thing_char = 'L'
206 class Thing_Psychedelic(Thing):
212 class Thing_PsychedelicSpawner(ThingSpawner):
214 child_type = 'Psychedelic'
218 class Thing_Bottle(Thing):
226 self.thing_char = '_'
230 all_players = [t for t in self.game.things if t.type_ == 'Player']
231 # TODO: refactor with ThingPlayer.prepare_multiprocessible_fov_stencil
232 # and ThingPlayer.fov_test
234 light_blockers = self.game.get_light_blockers()
235 obstacles = [t.position for t in self.game.things if t.blocks_light]
236 fov = FovMap(light_blockers, obstacles, self.game.maps,
237 self.position, fov_radius, self.game.get_map)
240 for p in all_players:
241 test_position = fov.target_yx(p.position[0], p.position[1])
242 if fov.inside(test_position) and fov[test_position] == '.':
243 visible_players += [p]
244 if len(visible_players) == 0:
245 self.sound('BOTTLE', 'no visible players in spin range')
246 pick = random.choice(visible_players)
247 self.sound('BOTTLE', 'BOTTLE picks: ' + pick.name)
251 class Thing_BottleSpawner(ThingSpawner):
252 child_type = 'Bottle'
256 class Thing_Hat(Thing):
259 design = ' +--+ ' + ' | | ' + '======'
264 new_design += self.design[12]
265 new_design += self.design[13]
266 new_design += self.design[6]
267 new_design += self.design[7]
268 new_design += self.design[0]
269 new_design += self.design[1]
270 new_design += self.design[14]
271 new_design += self.design[15]
272 new_design += self.design[8]
273 new_design += self.design[9]
274 new_design += self.design[2]
275 new_design += self.design[3]
276 new_design += self.design[16]
277 new_design += self.design[17]
278 new_design += self.design[10]
279 new_design += self.design[11]
280 new_design += self.design[4]
281 new_design += self.design[5]
282 self.design = ''.join(new_design)
286 class Thing_HatRemixer(Thing):
289 def accept(self, hat):
292 legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
294 new_design += random.choice(list(legal_chars))
295 hat.design = new_design
296 self.sound('HAT REMIXER', 'remixing a hat …')
297 self.game.changed = True
298 self.game.record_change(self.position, 'other')
303 class Thing_MusicPlayer(Thing):
308 next_song_start = datetime.datetime.now()
312 def __init__(self, *args, **kwargs):
313 super().__init__(*args, **kwargs)
314 self.next_song_start = datetime.datetime.now()
318 if (not self.playing) or len(self.playlist) == 0:
320 if datetime.datetime.now() > self.next_song_start:
321 self.playlist_index += 1
322 if self.playlist_index == len(self.playlist):
323 self.playlist_index = 0
327 song_data = self.playlist[self.playlist_index]
328 self.next_song_start = datetime.datetime.now() +\
329 datetime.timedelta(seconds=song_data[1])
330 self.sound('MUSICPLAYER', song_data[0])
331 self.game.changed = True
333 def interpret(self, command):
335 if command == 'HELP':
336 msg_lines += ['available commands:']
337 msg_lines += ['HELP – show this help']
338 msg_lines += ['ON/OFF – toggle playback on/off']
339 msg_lines += ['REWIND – return to start of playlist']
340 msg_lines += ['LIST – list programmed songs, durations']
341 msg_lines += ['SKIP – to skip to next song']
342 msg_lines += ['REPEAT – toggle playlist repeat on/off']
343 msg_lines += ['ADD LENGTH SONG – add SONG to playlist, with LENGTH in format "minutes:seconds", i.e. something like "0:47" or "11:02"']
345 elif command == 'LIST':
346 msg_lines += ['playlist:']
348 for entry in self.playlist:
349 minutes = entry[1] // 60
350 seconds = entry[1] % 60
352 seconds = '0%s' % seconds
353 selector = 'next:' if i == self.playlist_index else ' '
354 msg_lines += ['%s %s:%s – %s' % (selector, minutes, seconds, entry[0])]
357 elif command == 'ON/OFF':
358 self.playing = False if self.playing else True
359 self.game.changed = True
364 elif command == 'REMOVE':
365 if len(self.playlist) == 0:
366 return ['playlist already empty']
367 del self.playlist[max(0, self.playlist_index)]
368 self.playlist_index -= 1
369 if self.playlist_index < -1:
370 self.playlist_index = -1
371 self.game.changed = True
372 return ['removed song']
373 elif command == 'REWIND':
374 self.playlist_index = -1
375 self.next_song_start = datetime.datetime.now()
376 self.game.changed = True
377 return ['back at start of playlist']
378 elif command == 'SKIP':
379 self.next_song_start = datetime.datetime.now()
380 self.game.changed = True
382 elif command == 'REPEAT':
383 self.repeat = False if self.repeat else True
384 self.game.changed = True
386 return ['playlist repeat turned on']
388 return ['playlist repeat turned off']
389 elif command.startswith('ADD '):
390 tokens = command.split(' ', 2)
392 return ['wrong syntax, see HELP']
393 length = tokens[1].split(':')
395 return ['wrong syntax, see HELP']
397 minutes = int(length[0])
398 seconds = int(length[1])
400 return ['wrong syntax, see HELP']
401 self.playlist += [(tokens[2], minutes * 60 + seconds)]
402 self.game.changed = True
405 return ['cannot understand command']
409 class Thing_BottleDeposit(Thing):
414 if self.bottle_counter >= 3:
415 self.bottle_counter = 0
416 choice = random.choice(['MusicPlayer', 'Hat'])
417 self.game.add_thing(choice, self.position)
418 msg = 'here is a gift as a reward for ecological consciousness –'
419 if choice == 'MusicPlayer':
420 msg += 'pick it up and then use "command thing" on it!'
421 elif choice == 'Hat':
422 msg += 'pick it up and then use "(un-)wear" on it!'
423 self.sound('BOTTLE DEPOSITOR', msg)
426 self.bottle_counter += 1
427 self.sound('BOTTLE DEPOSITOR',
428 'thanks for this empty bottle – deposit %s more for a gift!' %
429 (3 - self.bottle_counter))
433 class Thing_Cookie(Thing):
437 def __init__(self, *args, **kwargs):
439 super().__init__(*args, **kwargs)
440 legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
441 self.thing_char = random.choice(list(legal_chars))
445 class Thing_CookieSpawner(Thing):
448 def accept(self, thing):
449 self.sound('OVEN', '*heat* *brrzt* here\'s a cookie!')
450 self.game.add_thing('Cookie', self.position)
454 class ThingAnimate(Thing):
457 def __init__(self, *args, **kwargs):
458 super().__init__(*args, **kwargs)
459 self.next_task = [None]
461 self.invalidate('fov')
462 self.invalidate('other') # currently redundant though
464 def invalidate(self, type_):
467 self._visible_terrain = None
468 self._visible_control = None
469 self.invalidate('other')
470 elif type_ == 'other':
471 self._seen_things = None
472 self._seen_annotation_positions = None
473 self._seen_portal_positions = None
475 def set_next_task(self, task_name, args=()):
476 task_class = self.game.tasks[task_name]
477 self.next_task = [task_class(self, args)]
479 def get_next_task(self):
480 if self.next_task[0]:
481 task = self.next_task[0]
482 self.next_task = [None]
484 task.todo += self.weariness * 10
488 if self.task is None:
489 self.task = self.get_next_task()
493 except (PlayError, GameError) as e:
497 if self.task.todo <= 0:
499 self.game.changed = True
500 self.task = self.get_next_task()
502 def prepare_multiprocessible_fov_stencil(self):
503 fov_radius = 3 if self.drunk > 0 else 12
504 light_blockers = self.game.get_light_blockers()
505 obstacles = [t.position for t in self.game.things if t.blocks_light]
506 self._fov = FovMap(light_blockers, obstacles, self.game.maps,
507 self.position, fov_radius, self.game.get_map)
509 def multiprocessible_fov_stencil(self):
510 self._fov.init_terrain()
513 def fov_stencil(self):
516 # due to the pre-multiprocessing in game.send_gamestate,
517 # the following should actually never be called
518 self.prepare_multiprocessible_fov_stencil()
519 self.multiprocessible_fov_stencil()
522 def fov_test(self, big_yx, little_yx):
523 test_position = self.fov_stencil.target_yx(big_yx, little_yx)
524 if self.fov_stencil.inside(test_position):
525 if self.fov_stencil[test_position] == '.':
529 def fov_stencil_map(self, map_type):
531 for yx in self.fov_stencil:
532 if self.fov_stencil[yx] == '.':
533 big_yx, little_yx = self.fov_stencil.source_yxyx(yx)
534 map_ = self.game.get_map(big_yx, map_type)
535 visible_terrain += map_[little_yx]
537 visible_terrain += ' '
538 return visible_terrain
541 def visible_terrain(self):
542 if self._visible_terrain:
543 return self._visible_terrain
544 self._visible_terrain = self.fov_stencil_map('normal')
545 return self._visible_terrain
548 def visible_control(self):
549 if self._visible_control:
550 return self._visible_control
551 self._visible_control = self.fov_stencil_map('control')
552 return self._visible_control
555 def seen_things(self):
556 if self._seen_things is not None:
557 return self._seen_things
558 self._seen_things = [t for t in self.game.things
559 if self.fov_test(*t.position)]
560 return self._seen_things
563 def seen_annotation_positions(self):
564 if self._seen_annotation_positions is not None:
565 return self._seen_annotation_positions
566 self._seen_annotation_positions = []
567 for big_yx in self.game.annotations:
568 for little_yx in [little_yx for little_yx
569 in self.game.annotations[big_yx]
570 if self.fov_test(big_yx, little_yx)]:
571 self._seen_annotation_positions += [(big_yx, little_yx)]
572 return self._seen_annotation_positions
575 def seen_portal_positions(self):
576 if self._seen_portal_positions is not None:
577 return self._seen_portal_positions
578 self._seen_portal_positions = []
579 for big_yx in self.game.portals:
580 for little_yx in [little_yx for little_yx
581 in self.game.portals[big_yx]
582 if self.fov_test(big_yx, little_yx)]:
583 self._seen_portal_positions += [(big_yx, little_yx)]
584 return self._seen_portal_positions
588 class Thing_Player(ThingAnimate):
595 def __init__(self, *args, **kwargs):
596 super().__init__(*args, **kwargs)
603 if self.tripping >= 0:
605 if self.need_for_toilet > 0:
606 terrain = self.game.maps[self.position[0]][self.position[1]]
607 if terrain in self.game.terrains:
608 terrain_type = self.game.terrains[terrain]
609 if 'toilet' in terrain_type.tags:
610 self.send_msg('CHAT "You use the toilet. What a relief!"')
611 self.need_for_toilet = 0
612 if self.need_for_toilet > 0:
613 if random.random() > 0.9999:
614 self.need_for_toilet += 1
615 self.game.changed = True
616 if 100000 * random.random() < self.need_for_toilet:
617 self.send_msg('CHAT "You need to go to a toilet."')
618 if self.need_for_toilet > 100:
619 self.send_msg('CHAT "You pee into your pants. Eww!"')
620 self.need_for_toilet = 0
621 self.game.changed = True
623 self.send_msg('CHAT "You sober up."')
624 self.invalidate('fov')
625 self.game.changed = True
626 if self.tripping == 0:
627 self.send_msg('DEFAULT_COLORS')
628 self.send_msg('CHAT "You sober up."')
629 self.game.changed = True
630 elif self.tripping > 0 and self.tripping % 250 == 0:
631 self.send_msg('RANDOM_COLORS')
632 self.game.changed = True
633 if random.random() > 0.9999:
636 elif self.weariness > 0:
638 self.game.changed = True
640 def send_msg(self, msg):
641 for c_id in self.game.sessions:
642 if self.game.sessions[c_id]['thing_id'] == self.id_:
643 self.game.io.send(msg, c_id)
652 def add_cookie_char(self, c):
653 if not self.name in self.game.players_hat_chars:
654 self.game.players_hat_chars[self.name] = ' #' # default
655 if not c in self.game.players_hat_chars[self.name]:
656 self.game.players_hat_chars[self.name] += c
658 def get_cookie_chars(self):
659 chars = ' #' # default
660 if self.name in self.game.players_hat_chars:
661 chars = self.game.players_hat_chars[self.name]
662 chars_split = list(chars)
664 return ''.join(chars_split)