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):
456 def __init__(self, *args, **kwargs):
457 super().__init__(*args, **kwargs)
458 self.next_task = [None]
460 self.invalidate('fov')
461 self.invalidate('other') # currently redundant though
463 def invalidate(self, type_):
466 self._visible_terrain = None
467 self._visible_control = None
468 self.invalidate('other')
469 elif type_ == 'other':
470 self._seen_things = None
471 self._seen_annotation_positions = None
472 self._seen_portal_positions = None
474 def set_next_task(self, task_name, args=()):
475 task_class = self.game.tasks[task_name]
476 self.next_task = [task_class(self, args)]
478 def get_next_task(self):
479 if self.next_task[0]:
480 task = self.next_task[0]
481 self.next_task = [None]
486 if self.task is None:
487 self.task = self.get_next_task()
491 except (PlayError, GameError) as e:
495 if self.task.todo <= 0:
497 self.game.changed = True
498 self.task = self.get_next_task()
500 def prepare_multiprocessible_fov_stencil(self):
501 fov_radius = 3 if self.drunk > 0 else 12
502 light_blockers = self.game.get_light_blockers()
503 obstacles = [t.position for t in self.game.things if t.blocks_light]
504 self._fov = FovMap(light_blockers, obstacles, self.game.maps,
505 self.position, fov_radius, self.game.get_map)
507 def multiprocessible_fov_stencil(self):
508 self._fov.init_terrain()
511 def fov_stencil(self):
514 # due to the pre-multiprocessing in game.send_gamestate,
515 # the following should actually never be called
516 self.prepare_multiprocessible_fov_stencil()
517 self.multiprocessible_fov_stencil()
520 def fov_test(self, big_yx, little_yx):
521 test_position = self.fov_stencil.target_yx(big_yx, little_yx)
522 if self.fov_stencil.inside(test_position):
523 if self.fov_stencil[test_position] == '.':
527 def fov_stencil_map(self, map_type):
529 for yx in self.fov_stencil:
530 if self.fov_stencil[yx] == '.':
531 big_yx, little_yx = self.fov_stencil.source_yxyx(yx)
532 map_ = self.game.get_map(big_yx, map_type)
533 visible_terrain += map_[little_yx]
535 visible_terrain += ' '
536 return visible_terrain
539 def visible_terrain(self):
540 if self._visible_terrain:
541 return self._visible_terrain
542 self._visible_terrain = self.fov_stencil_map('normal')
543 return self._visible_terrain
546 def visible_control(self):
547 if self._visible_control:
548 return self._visible_control
549 self._visible_control = self.fov_stencil_map('control')
550 return self._visible_control
553 def seen_things(self):
554 if self._seen_things is not None:
555 return self._seen_things
556 self._seen_things = [t for t in self.game.things
557 if self.fov_test(*t.position)]
558 return self._seen_things
561 def seen_annotation_positions(self):
562 if self._seen_annotation_positions is not None:
563 return self._seen_annotation_positions
564 self._seen_annotation_positions = []
565 for big_yx in self.game.annotations:
566 for little_yx in [little_yx for little_yx
567 in self.game.annotations[big_yx]
568 if self.fov_test(big_yx, little_yx)]:
569 self._seen_annotation_positions += [(big_yx, little_yx)]
570 return self._seen_annotation_positions
573 def seen_portal_positions(self):
574 if self._seen_portal_positions is not None:
575 return self._seen_portal_positions
576 self._seen_portal_positions = []
577 for big_yx in self.game.portals:
578 for little_yx in [little_yx for little_yx
579 in self.game.portals[big_yx]
580 if self.fov_test(big_yx, little_yx)]:
581 self._seen_portal_positions += [(big_yx, little_yx)]
582 return self._seen_portal_positions
586 class Thing_Player(ThingAnimate):
593 def __init__(self, *args, **kwargs):
594 super().__init__(*args, **kwargs)
601 if self.tripping >= 0:
603 if self.need_for_toilet > 0:
604 self.need_for_toilet += 1
605 terrain = self.game.maps[self.position[0]][self.position[1]]
606 if terrain in self.game.terrains:
607 terrain_type = self.game.terrains[terrain]
608 if 'toilet' in terrain_type.tags:
609 self.send_msg('CHAT "You use the toilet. What a relief!"')
610 self.need_for_toilet = 0
611 if 10000 * random.random() < self.need_for_toilet / 100000:
612 self.send_msg('CHAT "You need to go to a toilet."')
613 if self.need_for_toilet > 1000000:
614 self.send_msg('CHAT "You pee into your pants. Eww!"')
615 self.need_for_toilet = 0
617 self.send_msg('CHAT "You sober up."')
618 self.invalidate('fov')
619 self.game.changed = True
620 if self.tripping == 0:
621 self.send_msg('DEFAULT_COLORS')
622 self.send_msg('CHAT "You sober up."')
623 self.game.changed = True
624 elif self.tripping > 0 and self.tripping % 250 == 0:
625 self.send_msg('RANDOM_COLORS')
626 self.game.changed = True
628 def send_msg(self, msg):
629 for c_id in self.game.sessions:
630 if self.game.sessions[c_id]['thing_id'] == self.id_:
631 self.game.io.send(msg, c_id)
640 def add_cookie_char(self, c):
641 if not self.name in self.game.players_hat_chars:
642 self.game.players_hat_chars[self.name] = ' #' # default
643 if not c in self.game.players_hat_chars[self.name]:
644 self.game.players_hat_chars[self.name] += c
646 def get_cookie_chars(self):
647 chars = ' #' # default
648 if self.name in self.game.players_hat_chars:
649 chars = self.game.players_hat_chars[self.name]
650 chars_split = list(chars)
652 return ''.join(chars_split)