1 from plomrogue.errors import GameError, PlayError
2 from plomrogue.mapping import YX
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):
29 def __init__(self, *args, **kwargs):
30 super().__init__(*args, **kwargs)
37 return self.__class__.get_type()
41 return cls.__name__[len('Thing_'):]
43 def sound(self, name, msg):
44 from plomrogue.mapping import DijkstraMap
47 def lower_msg_by_volume(msg, volume, largest_audible_distance,
50 factor = largest_audible_distance / 4
57 in_url = False if in_url else True
59 while random.random() > volume * factor:
62 elif c != '.' and c != ' ':
70 largest_audible_distance = 20
71 # player's don't block sound
72 obstacles = [t.position for t in self.game.things
73 if t.blocking and t.type_ != 'Player']
74 sound_blockers = self.game.get_sound_blockers()
75 dijkstra_map = DijkstraMap(sound_blockers, obstacles, self.game.maps,
76 self.position, largest_audible_distance,
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 self.game.io.send('CHATFACE %s' % self.id_, c_id)
98 if self.type_ == 'Player' and hasattr(self, 'thing_char'):
99 symbol = '/@' + self.thing_char
100 self.game.io.send('CHAT ' +
101 quote('vol:%.f%s %s%s: %s' % (volume * 100, '%',
102 lowered_nick, symbol,
108 class Thing_Item(Thing):
114 class ThingSpawner(Thing):
118 for t in [t for t in self.game.things
119 if t != self and t.position == self.position]:
121 self.game.add_thing(self.child_type, self.position)
125 class Thing_ItemSpawner(ThingSpawner):
130 class Thing_SpawnPointSpawner(ThingSpawner):
131 child_type = 'SpawnPoint'
135 class Thing_SpawnPoint(Thing):
142 class Thing_DoorSpawner(ThingSpawner):
147 class Thing_Door(Thing):
154 self.blocking = False
159 self.thing_char = '#'
162 self.portable = False
169 class Thing_Bottle(Thing):
177 self.thing_char = '_'
182 all_players = [t for t in self.game.things if t.type_ == 'Player']
183 # TODO: refactor with ThingPlayer.prepare_multiprocessible_fov_stencil
184 # and ThingPlayer.fov_test
185 fov_map_class = self.game.map_geometry.fov_map_class
187 light_blockers = self.game.get_light_blockers()
188 obstacles = [t.position for t in self.game.things if t.blocking]
189 fov = fov_map_class(light_blockers, obstacles, self.game.maps,
190 self.position, fov_radius, self.game.get_map)
193 for p in all_players:
194 test_position = fov.target_yx(p.position[0], p.position[1])
195 if fov.inside(test_position) and fov[test_position] == '.':
196 visible_players += [p]
197 if len(visible_players) == 0:
198 self.sound('BOTTLE', 'no visible players in spin range')
199 pick = random.choice(visible_players)
200 self.sound('BOTTLE', 'BOTTLE picks: ' + pick.name)
204 class Thing_BottleSpawner(ThingSpawner):
205 child_type = 'Bottle'
209 class Thing_Hat(Thing):
212 design = ' +--+ ' + ' | | ' + '======'
217 new_design += self.design[12]
218 new_design += self.design[13]
219 new_design += self.design[6]
220 new_design += self.design[7]
221 new_design += self.design[0]
222 new_design += self.design[1]
223 new_design += self.design[14]
224 new_design += self.design[15]
225 new_design += self.design[8]
226 new_design += self.design[9]
227 new_design += self.design[2]
228 new_design += self.design[3]
229 new_design += self.design[16]
230 new_design += self.design[17]
231 new_design += self.design[10]
232 new_design += self.design[11]
233 new_design += self.design[4]
234 new_design += self.design[5]
235 self.design = ''.join(new_design)
239 class Thing_HatRemixer(Thing):
242 def accept(self, hat):
245 legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
247 new_design += random.choice(list(legal_chars))
248 hat.design = new_design
249 self.sound('HAT REMIXER', 'remixing a hat …')
250 self.game.changed = True
251 self.game.record_change(self.position, 'other')
256 class Thing_MusicPlayer(Thing):
261 next_song_start = datetime.datetime.now()
265 def __init__(self, *args, **kwargs):
266 super().__init__(*args, **kwargs)
267 self.next_song_start = datetime.datetime.now()
271 if (not self.playing) or len(self.playlist) == 0:
273 if datetime.datetime.now() > self.next_song_start:
274 self.playlist_index += 1
275 if self.playlist_index == len(self.playlist):
276 self.playlist_index = 0
280 song_data = self.playlist[self.playlist_index]
281 self.next_song_start = datetime.datetime.now() +\
282 datetime.timedelta(seconds=song_data[1])
283 self.sound('MUSICPLAYER', song_data[0])
284 self.game.changed = True
286 def interpret(self, command):
288 if command == 'HELP':
289 msg_lines += ['available commands:']
290 msg_lines += ['HELP – show this help']
291 msg_lines += ['ON/OFF – toggle playback on/off']
292 msg_lines += ['REWIND – return to start of playlist']
293 msg_lines += ['LIST – list programmed songs, durations']
294 msg_lines += ['SKIP – to skip to next song']
295 msg_lines += ['REPEAT – toggle playlist repeat on/off']
296 msg_lines += ['ADD LENGTH SONG – add SONG to playlist, with LENGTH in format "minutes:seconds", i.e. something like "0:47" or "11:02"']
298 elif command == 'LIST':
299 msg_lines += ['playlist:']
301 for entry in self.playlist:
302 minutes = entry[1] // 60
303 seconds = entry[1] % 60
305 seconds = '0%s' % seconds
306 selector = 'next:' if i == self.playlist_index else ' '
307 msg_lines += ['%s %s:%s – %s' % (selector, minutes, seconds, entry[0])]
310 elif command == 'ON/OFF':
311 self.playing = False if self.playing else True
312 self.game.changed = True
317 elif command == 'REMOVE':
318 if len(self.playlist) == 0:
319 return ['playlist already empty']
320 del self.playlist[max(0, self.playlist_index)]
321 self.playlist_index -= 1
322 if self.playlist_index < -1:
323 self.playlist_index = -1
324 self.game.changed = True
325 return ['removed song']
326 elif command == 'REWIND':
327 self.playlist_index = -1
328 self.next_song_start = datetime.datetime.now()
329 self.game.changed = True
330 return ['back at start of playlist']
331 elif command == 'SKIP':
332 self.next_song_start = datetime.datetime.now()
333 self.game.changed = True
335 elif command == 'REPEAT':
336 self.repeat = False if self.repeat else True
337 self.game.changed = True
339 return ['playlist repeat turned on']
341 return ['playlist repeat turned off']
342 elif command.startswith('ADD '):
343 tokens = command.split(' ', 2)
345 return ['wrong syntax, see HELP']
346 length = tokens[1].split(':')
348 return ['wrong syntax, see HELP']
350 minutes = int(length[0])
351 seconds = int(length[1])
353 return ['wrong syntax, see HELP']
354 self.playlist += [(tokens[2], minutes * 60 + seconds)]
355 self.game.changed = True
358 return ['cannot understand command']
362 class Thing_BottleDeposit(Thing):
367 if self.bottle_counter >= 3:
368 self.bottle_counter = 0
369 choice = random.choice(['MusicPlayer', 'Hat'])
370 self.game.add_thing(choice, self.position)
371 msg = 'here is a gift as a reward for ecological consciousness –'
372 if choice == 'MusicPlayer':
373 msg += 'pick it up and then use "command thing" on it!'
374 elif choice == 'Hat':
375 msg += 'pick it up and then use "(un-)wear" on it!'
376 self.sound('BOTTLE DEPOSITOR', msg)
379 self.bottle_counter += 1
380 self.sound('BOTTLE DEPOSITOR',
381 'thanks for this empty bottle – deposit %s more for a gift!' %
382 (3 - self.bottle_counter))
386 class Thing_Cookie(Thing):
390 def __init__(self, *args, **kwargs):
392 super().__init__(*args, **kwargs)
393 legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
394 self.thing_char = random.choice(list(legal_chars))
398 class Thing_CookieSpawner(Thing):
401 def accept(self, thing):
402 self.sound('OVEN', '*heat* *brrzt* here\'s a cookie!')
403 self.game.add_thing('Cookie', self.position)
407 class ThingAnimate(Thing):
411 def __init__(self, *args, **kwargs):
412 super().__init__(*args, **kwargs)
413 self.next_task = [None]
415 self.invalidate('fov')
416 self.invalidate('other') # currently redundant though
418 def invalidate(self, type_):
421 self._visible_terrain = None
422 self._visible_control = None
423 self.invalidate('other')
424 elif type_ == 'other':
425 self._seen_things = None
426 self._seen_annotation_positions = None
427 self._seen_portal_positions = None
429 def set_next_task(self, task_name, args=()):
430 task_class = self.game.tasks[task_name]
431 self.next_task = [task_class(self, args)]
433 def get_next_task(self):
434 if self.next_task[0]:
435 task = self.next_task[0]
436 self.next_task = [None]
443 for c_id in self.game.sessions:
444 if self.game.sessions[c_id]['thing_id'] == self.id_:
445 # TODO: refactor with self.send_msg
446 self.game.io.send('DEFAULT_COLORS', c_id)
447 self.game.io.send('CHAT "You sober up."', c_id)
448 self.invalidate('fov')
450 self.game.changed = True
451 if self.task is None:
452 self.task = self.get_next_task()
456 except (PlayError, GameError) as e:
460 if self.task.todo <= 0:
462 self.game.changed = True
463 self.task = self.get_next_task()
465 def prepare_multiprocessible_fov_stencil(self):
466 fov_map_class = self.game.map_geometry.fov_map_class
467 fov_radius = 3 if self.drunk > 0 else 12
468 light_blockers = self.game.get_light_blockers()
469 obstacles = [t.position for t in self.game.things if t.blocking]
470 self._fov = fov_map_class(light_blockers, obstacles, self.game.maps,
471 self.position, fov_radius, self.game.get_map)
473 def multiprocessible_fov_stencil(self):
474 self._fov.init_terrain()
477 def fov_stencil(self):
480 # due to the pre-multiprocessing in game.send_gamestate,
481 # the following should actually never be called
482 self.prepare_multiprocessible_fov_stencil()
483 self.multiprocessible_fov_stencil()
486 def fov_stencil_make(self):
489 def fov_test(self, big_yx, little_yx):
490 test_position = self.fov_stencil.target_yx(big_yx, little_yx)
491 if self.fov_stencil.inside(test_position):
492 if self.fov_stencil[test_position] == '.':
496 def fov_stencil_map(self, map_type):
498 for yx in self.fov_stencil:
499 if self.fov_stencil[yx] == '.':
500 big_yx, little_yx = self.fov_stencil.source_yxyx(yx)
501 map_ = self.game.get_map(big_yx, map_type)
502 visible_terrain += map_[little_yx]
504 visible_terrain += ' '
505 return visible_terrain
508 def visible_terrain(self):
509 if self._visible_terrain:
510 return self._visible_terrain
511 self._visible_terrain = self.fov_stencil_map('normal')
512 return self._visible_terrain
515 def visible_control(self):
516 if self._visible_control:
517 return self._visible_control
518 self._visible_control = self.fov_stencil_map('control')
519 return self._visible_control
522 def seen_things(self):
523 if self._seen_things is not None:
524 return self._seen_things
525 self._seen_things = [t for t in self.game.things
526 if self.fov_test(*t.position)]
527 return self._seen_things
530 def seen_annotation_positions(self):
531 if self._seen_annotation_positions is not None:
532 return self._seen_annotation_positions
533 self._seen_annotation_positions = []
534 for big_yx in self.game.annotations:
535 for little_yx in [little_yx for little_yx
536 in self.game.annotations[big_yx]
537 if self.fov_test(big_yx, little_yx)]:
538 self._seen_annotation_positions += [(big_yx, little_yx)]
539 return self._seen_annotation_positions
542 def seen_portal_positions(self):
543 if self._seen_portal_positions is not None:
544 return self._seen_portal_positions
545 self._seen_portal_positions = []
546 for big_yx in self.game.portals:
547 for little_yx in [little_yx for little_yx
548 in self.game.portals[big_yx]
549 if self.fov_test(big_yx, little_yx)]:
550 self._seen_portal_positions += [(big_yx, little_yx)]
551 return self._seen_portal_positions
555 class Thing_Player(ThingAnimate):
558 def __init__(self, *args, **kwargs):
559 super().__init__(*args, **kwargs)
562 def send_msg(self, msg):
563 for c_id in self.game.sessions:
564 if self.game.sessions[c_id]['thing_id'] == self.id_:
565 self.game.io.send(msg, c_id)
574 def add_cookie_char(self, c):
575 if not self.name in self.game.players_hat_chars:
576 self.game.players_hat_chars[self.name] = ' #' # default
577 if not c in self.game.players_hat_chars[self.name]:
578 self.game.players_hat_chars[self.name] += c
580 def get_cookie_chars(self):
581 if self.name in self.game.players_hat_chars:
582 return self.game.players_hat_chars[self.name]
583 return ' #' # default