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 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):
169 class Thing_Door(ThingInstallable):
171 blocks_movement = False
174 self.blocks_movement = False
175 self.blocks_light = False
176 self.blocks_sound = False
180 self.blocks_movement = True
181 self.blocks_light = True
182 self.blocks_sound = True
183 self.thing_char = '#'
187 class Thing_Psychedelic(Thing):
193 class Thing_PsychedelicSpawner(ThingSpawner):
195 child_type = 'Psychedelic'
199 class Thing_Bottle(Thing):
207 self.thing_char = '_'
211 all_players = [t for t in self.game.things if t.type_ == 'Player']
212 # TODO: refactor with ThingPlayer.prepare_multiprocessible_fov_stencil
213 # and ThingPlayer.fov_test
215 light_blockers = self.game.get_light_blockers()
216 obstacles = [t.position for t in self.game.things if t.blocks_light]
217 fov = FovMap(light_blockers, obstacles, self.game.maps,
218 self.position, fov_radius, self.game.get_map)
221 for p in all_players:
222 test_position = fov.target_yx(p.position[0], p.position[1])
223 if fov.inside(test_position) and fov[test_position] == '.':
224 visible_players += [p]
225 if len(visible_players) == 0:
226 self.sound('BOTTLE', 'no visible players in spin range')
227 pick = random.choice(visible_players)
228 self.sound('BOTTLE', 'BOTTLE picks: ' + pick.name)
232 class Thing_BottleSpawner(ThingSpawner):
233 child_type = 'Bottle'
237 class Thing_Hat(Thing):
240 design = ' +--+ ' + ' | | ' + '======'
245 new_design += self.design[12]
246 new_design += self.design[13]
247 new_design += self.design[6]
248 new_design += self.design[7]
249 new_design += self.design[0]
250 new_design += self.design[1]
251 new_design += self.design[14]
252 new_design += self.design[15]
253 new_design += self.design[8]
254 new_design += self.design[9]
255 new_design += self.design[2]
256 new_design += self.design[3]
257 new_design += self.design[16]
258 new_design += self.design[17]
259 new_design += self.design[10]
260 new_design += self.design[11]
261 new_design += self.design[4]
262 new_design += self.design[5]
263 self.design = ''.join(new_design)
267 class Thing_HatRemixer(Thing):
270 def accept(self, hat):
273 legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
275 new_design += random.choice(list(legal_chars))
276 hat.design = new_design
277 self.sound('HAT REMIXER', 'remixing a hat …')
278 self.game.changed = True
279 self.game.record_change(self.position, 'other')
284 class Thing_MusicPlayer(Thing):
289 next_song_start = datetime.datetime.now()
293 def __init__(self, *args, **kwargs):
294 super().__init__(*args, **kwargs)
295 self.next_song_start = datetime.datetime.now()
299 if (not self.playing) or len(self.playlist) == 0:
301 if datetime.datetime.now() > self.next_song_start:
302 self.playlist_index += 1
303 if self.playlist_index == len(self.playlist):
304 self.playlist_index = 0
308 song_data = self.playlist[self.playlist_index]
309 self.next_song_start = datetime.datetime.now() +\
310 datetime.timedelta(seconds=song_data[1])
311 self.sound('MUSICPLAYER', song_data[0])
312 self.game.changed = True
314 def interpret(self, command):
316 if command == 'HELP':
317 msg_lines += ['available commands:']
318 msg_lines += ['HELP – show this help']
319 msg_lines += ['ON/OFF – toggle playback on/off']
320 msg_lines += ['REWIND – return to start of playlist']
321 msg_lines += ['LIST – list programmed songs, durations']
322 msg_lines += ['SKIP – to skip to next song']
323 msg_lines += ['REPEAT – toggle playlist repeat on/off']
324 msg_lines += ['ADD LENGTH SONG – add SONG to playlist, with LENGTH in format "minutes:seconds", i.e. something like "0:47" or "11:02"']
326 elif command == 'LIST':
327 msg_lines += ['playlist:']
329 for entry in self.playlist:
330 minutes = entry[1] // 60
331 seconds = entry[1] % 60
333 seconds = '0%s' % seconds
334 selector = 'next:' if i == self.playlist_index else ' '
335 msg_lines += ['%s %s:%s – %s' % (selector, minutes, seconds, entry[0])]
338 elif command == 'ON/OFF':
339 self.playing = False if self.playing else True
340 self.game.changed = True
345 elif command == 'REMOVE':
346 if len(self.playlist) == 0:
347 return ['playlist already empty']
348 del self.playlist[max(0, self.playlist_index)]
349 self.playlist_index -= 1
350 if self.playlist_index < -1:
351 self.playlist_index = -1
352 self.game.changed = True
353 return ['removed song']
354 elif command == 'REWIND':
355 self.playlist_index = -1
356 self.next_song_start = datetime.datetime.now()
357 self.game.changed = True
358 return ['back at start of playlist']
359 elif command == 'SKIP':
360 self.next_song_start = datetime.datetime.now()
361 self.game.changed = True
363 elif command == 'REPEAT':
364 self.repeat = False if self.repeat else True
365 self.game.changed = True
367 return ['playlist repeat turned on']
369 return ['playlist repeat turned off']
370 elif command.startswith('ADD '):
371 tokens = command.split(' ', 2)
373 return ['wrong syntax, see HELP']
374 length = tokens[1].split(':')
376 return ['wrong syntax, see HELP']
378 minutes = int(length[0])
379 seconds = int(length[1])
381 return ['wrong syntax, see HELP']
382 self.playlist += [(tokens[2], minutes * 60 + seconds)]
383 self.game.changed = True
386 return ['cannot understand command']
390 class Thing_BottleDeposit(Thing):
395 if self.bottle_counter >= 3:
396 self.bottle_counter = 0
397 choice = random.choice(['MusicPlayer', 'Hat'])
398 self.game.add_thing(choice, self.position)
399 msg = 'here is a gift as a reward for ecological consciousness –'
400 if choice == 'MusicPlayer':
401 msg += 'pick it up and then use "command thing" on it!'
402 elif choice == 'Hat':
403 msg += 'pick it up and then use "(un-)wear" on it!'
404 self.sound('BOTTLE DEPOSITOR', msg)
407 self.bottle_counter += 1
408 self.sound('BOTTLE DEPOSITOR',
409 'thanks for this empty bottle – deposit %s more for a gift!' %
410 (3 - self.bottle_counter))
414 class Thing_Cookie(Thing):
418 def __init__(self, *args, **kwargs):
420 super().__init__(*args, **kwargs)
421 legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
422 self.thing_char = random.choice(list(legal_chars))
426 class Thing_CookieSpawner(Thing):
429 def accept(self, thing):
430 self.sound('OVEN', '*heat* *brrzt* here\'s a cookie!')
431 self.game.add_thing('Cookie', self.position)
435 class ThingAnimate(Thing):
437 def __init__(self, *args, **kwargs):
438 super().__init__(*args, **kwargs)
439 self.next_task = [None]
441 self.invalidate('fov')
442 self.invalidate('other') # currently redundant though
444 def invalidate(self, type_):
447 self._visible_terrain = None
448 self._visible_control = None
449 self.invalidate('other')
450 elif type_ == 'other':
451 self._seen_things = None
452 self._seen_annotation_positions = None
453 self._seen_portal_positions = None
455 def set_next_task(self, task_name, args=()):
456 task_class = self.game.tasks[task_name]
457 self.next_task = [task_class(self, args)]
459 def get_next_task(self):
460 if self.next_task[0]:
461 task = self.next_task[0]
462 self.next_task = [None]
467 if self.task is None:
468 self.task = self.get_next_task()
472 except (PlayError, GameError) as e:
476 if self.task.todo <= 0:
478 self.game.changed = True
479 self.task = self.get_next_task()
481 def prepare_multiprocessible_fov_stencil(self):
482 fov_radius = 3 if self.drunk > 0 else 12
483 light_blockers = self.game.get_light_blockers()
484 obstacles = [t.position for t in self.game.things if t.blocks_light]
485 self._fov = FovMap(light_blockers, obstacles, self.game.maps,
486 self.position, fov_radius, self.game.get_map)
488 def multiprocessible_fov_stencil(self):
489 self._fov.init_terrain()
492 def fov_stencil(self):
495 # due to the pre-multiprocessing in game.send_gamestate,
496 # the following should actually never be called
497 self.prepare_multiprocessible_fov_stencil()
498 self.multiprocessible_fov_stencil()
501 def fov_test(self, big_yx, little_yx):
502 test_position = self.fov_stencil.target_yx(big_yx, little_yx)
503 if self.fov_stencil.inside(test_position):
504 if self.fov_stencil[test_position] == '.':
508 def fov_stencil_map(self, map_type):
510 for yx in self.fov_stencil:
511 if self.fov_stencil[yx] == '.':
512 big_yx, little_yx = self.fov_stencil.source_yxyx(yx)
513 map_ = self.game.get_map(big_yx, map_type)
514 visible_terrain += map_[little_yx]
516 visible_terrain += ' '
517 return visible_terrain
520 def visible_terrain(self):
521 if self._visible_terrain:
522 return self._visible_terrain
523 self._visible_terrain = self.fov_stencil_map('normal')
524 return self._visible_terrain
527 def visible_control(self):
528 if self._visible_control:
529 return self._visible_control
530 self._visible_control = self.fov_stencil_map('control')
531 return self._visible_control
534 def seen_things(self):
535 if self._seen_things is not None:
536 return self._seen_things
537 self._seen_things = [t for t in self.game.things
538 if self.fov_test(*t.position)]
539 return self._seen_things
542 def seen_annotation_positions(self):
543 if self._seen_annotation_positions is not None:
544 return self._seen_annotation_positions
545 self._seen_annotation_positions = []
546 for big_yx in self.game.annotations:
547 for little_yx in [little_yx for little_yx
548 in self.game.annotations[big_yx]
549 if self.fov_test(big_yx, little_yx)]:
550 self._seen_annotation_positions += [(big_yx, little_yx)]
551 return self._seen_annotation_positions
554 def seen_portal_positions(self):
555 if self._seen_portal_positions is not None:
556 return self._seen_portal_positions
557 self._seen_portal_positions = []
558 for big_yx in self.game.portals:
559 for little_yx in [little_yx for little_yx
560 in self.game.portals[big_yx]
561 if self.fov_test(big_yx, little_yx)]:
562 self._seen_portal_positions += [(big_yx, little_yx)]
563 return self._seen_portal_positions
567 class Thing_Player(ThingAnimate):
574 def __init__(self, *args, **kwargs):
575 super().__init__(*args, **kwargs)
582 if self.tripping >= 0:
584 if self.need_for_toilet > 0:
585 self.need_for_toilet += 1
586 terrain = self.game.maps[self.position[0]][self.position[1]]
587 if terrain in self.game.terrains:
588 terrain_type = self.game.terrains[terrain]
589 if 'toilet' in terrain_type.tags:
590 self.send_msg('CHAT "You use the toilet. What a relief!"')
591 self.need_for_toilet = 0
592 if 10000 * random.random() < self.need_for_toilet / 100000:
593 self.send_msg('CHAT "You need to go to a toilet."')
594 if self.need_for_toilet > 1000000:
595 self.send_msg('CHAT "You pee into your pants. Eww!"')
596 self.need_for_toilet = 0
598 self.send_msg('CHAT "You sober up."')
599 self.invalidate('fov')
600 self.game.changed = True
601 if self.tripping == 0:
602 self.send_msg('DEFAULT_COLORS')
603 self.send_msg('CHAT "You sober up."')
604 self.game.changed = True
605 elif self.tripping > 0 and self.tripping % 250 == 0:
606 self.send_msg('RANDOM_COLORS')
607 self.game.changed = True
609 def send_msg(self, msg):
610 for c_id in self.game.sessions:
611 if self.game.sessions[c_id]['thing_id'] == self.id_:
612 self.game.io.send(msg, c_id)
621 def add_cookie_char(self, c):
622 if not self.name in self.game.players_hat_chars:
623 self.game.players_hat_chars[self.name] = ' #' # default
624 if not c in self.game.players_hat_chars[self.name]:
625 self.game.players_hat_chars[self.name] += c
627 def get_cookie_chars(self):
628 chars = ' #' # default
629 if self.name in self.game.players_hat_chars:
630 chars = self.game.players_hat_chars[self.name]
631 chars_split = list(chars)
633 return ''.join(chars_split)