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 (or should they?)
72 things = [t for t in self.game.things if t.type_ != 'Player']
73 sound_blockers = self.game.get_sound_blockers()
74 dijkstra_map = DijkstraMap(sound_blockers, things, self.game.maps, self.position,
75 largest_audible_distance, self.game.get_map)
77 for m in re.finditer('https?://[^\s]+', msg):
78 url_limits += [m.start(), m.end()]
79 for c_id in self.game.sessions:
80 listener = self.game.get_player(c_id)
81 target_yx = dijkstra_map.target_yx(*listener.position, True)
84 listener_distance = dijkstra_map[target_yx]
85 if listener_distance > largest_audible_distance:
87 volume = 1 / max(1, listener_distance)
88 lowered_msg = lower_msg_by_volume(msg, volume,
89 largest_audible_distance,
91 lowered_nick = lower_msg_by_volume(name, volume,
92 largest_audible_distance)
94 if listener.fov_test(self.position[0], self.position[1]):
95 self.game.io.send('CHATFACE %s' % self.id_, c_id)
96 if self.type_ == 'Player' and hasattr(self, 'thing_char'):
97 symbol = '/@' + self.thing_char
98 self.game.io.send('CHAT ' +
99 quote('vol:%.f%s %s%s: %s' % (volume * 100, '%',
100 lowered_nick, symbol,
106 class Thing_Item(Thing):
112 class ThingSpawner(Thing):
116 for t in [t for t in self.game.things
117 if t != self and t.position == self.position]:
119 self.game.add_thing(self.child_type, self.position)
120 # self.game.changed = True handled by add_thing
124 class Thing_ItemSpawner(ThingSpawner):
129 class Thing_SpawnPointSpawner(ThingSpawner):
130 child_type = 'SpawnPoint'
134 class Thing_SpawnPoint(Thing):
141 class Thing_DoorSpawner(ThingSpawner):
146 class Thing_Door(Thing):
153 self.blocking = False
158 self.thing_char = '#'
161 self.portable = False
168 class Thing_Bottle(Thing):
176 self.thing_char = '_'
181 all_players = [t for t in self.game.things if t.type_ == 'Player']
182 # TODO: refactor with ThingPlayer.prepare_multiprocessible_fov_stencil
183 # and ThingPlayer.fov_test
184 fov_map_class = self.game.map_geometry.fov_map_class
186 light_blockers = self.game.get_light_blockers()
187 fov = fov_map_class(light_blockers, self.game.things, self.game.maps,
188 self.position, fov_radius, self.game.get_map)
191 for p in all_players:
192 test_position = fov.target_yx(p.position[0], p.position[1])
193 if fov.inside(test_position) and fov[test_position] == '.':
194 visible_players += [p]
195 if len(visible_players) == 0:
196 self.sound('BOTTLE', 'no visible players in spin range')
197 pick = random.choice(visible_players)
198 self.sound('BOTTLE', 'BOTTLE picks: ' + pick.name)
202 class Thing_BottleSpawner(ThingSpawner):
203 child_type = 'Bottle'
207 class Thing_Hat(Thing):
210 design = ' +--+ ' + ' | | ' + '======'
215 new_design += self.design[12]
216 new_design += self.design[13]
217 new_design += self.design[6]
218 new_design += self.design[7]
219 new_design += self.design[0]
220 new_design += self.design[1]
221 new_design += self.design[14]
222 new_design += self.design[15]
223 new_design += self.design[8]
224 new_design += self.design[9]
225 new_design += self.design[2]
226 new_design += self.design[3]
227 new_design += self.design[16]
228 new_design += self.design[17]
229 new_design += self.design[10]
230 new_design += self.design[11]
231 new_design += self.design[4]
232 new_design += self.design[5]
233 self.design = ''.join(new_design)
237 class Thing_HatRemixer(Thing):
240 def accept(self, hat):
243 legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
245 new_design += random.choice(list(legal_chars))
246 hat.design = new_design
247 self.sound('HAT REMIXER', 'remixing a hat …')
248 self.game.changed = True
249 self.game.record_change(self.position, 'other')
254 class Thing_MusicPlayer(Thing):
259 next_song_start = datetime.datetime.now()
263 def __init__(self, *args, **kwargs):
264 super().__init__(*args, **kwargs)
265 self.next_song_start = datetime.datetime.now()
269 if (not self.playing) or len(self.playlist) == 0:
271 if datetime.datetime.now() > self.next_song_start:
272 self.playlist_index += 1
273 if self.playlist_index == len(self.playlist):
274 self.playlist_index = 0
278 song_data = self.playlist[self.playlist_index]
279 self.next_song_start = datetime.datetime.now() +\
280 datetime.timedelta(seconds=song_data[1])
281 self.sound('MUSICPLAYER', song_data[0])
282 self.game.changed = True
284 def interpret(self, command):
286 if command == 'HELP':
287 msg_lines += ['available commands:']
288 msg_lines += ['HELP – show this help']
289 msg_lines += ['ON/OFF – toggle playback on/off']
290 msg_lines += ['REWIND – return to start of playlist']
291 msg_lines += ['LIST – list programmed songs, durations']
292 msg_lines += ['SKIP – to skip to next song']
293 msg_lines += ['REPEAT – toggle playlist repeat on/off']
294 msg_lines += ['ADD LENGTH SONG – add SONG to playlist, with LENGTH in format "minutes:seconds", i.e. something like "0:47" or "11:02"']
296 elif command == 'LIST':
297 msg_lines += ['playlist:']
299 for entry in self.playlist:
300 minutes = entry[1] // 60
301 seconds = entry[1] % 60
303 seconds = '0%s' % seconds
304 selector = 'next:' if i == self.playlist_index else ' '
305 msg_lines += ['%s %s:%s – %s' % (selector, minutes, seconds, entry[0])]
308 elif command == 'ON/OFF':
309 self.playing = False if self.playing else True
310 self.game.changed = True
315 elif command == 'REMOVE':
316 if len(self.playlist) == 0:
317 return ['playlist already empty']
318 del self.playlist[max(0, self.playlist_index)]
319 self.playlist_index -= 1
320 if self.playlist_index < -1:
321 self.playlist_index = -1
322 self.game.changed = True
323 return ['removed song']
324 elif command == 'REWIND':
325 self.playlist_index = -1
326 self.next_song_start = datetime.datetime.now()
327 self.game.changed = True
328 return ['back at start of playlist']
329 elif command == 'SKIP':
330 self.next_song_start = datetime.datetime.now()
331 self.game.changed = True
333 elif command == 'REPEAT':
334 self.repeat = False if self.repeat else True
335 self.game.changed = True
337 return ['playlist repeat turned on']
339 return ['playlist repeat turned off']
340 elif command.startswith('ADD '):
341 tokens = command.split(' ', 2)
343 return ['wrong syntax, see HELP']
344 length = tokens[1].split(':')
346 return ['wrong syntax, see HELP']
348 minutes = int(length[0])
349 seconds = int(length[1])
351 return ['wrong syntax, see HELP']
352 self.playlist += [(tokens[2], minutes * 60 + seconds)]
353 self.game.changed = True
356 return ['cannot understand command']
360 class Thing_BottleDeposit(Thing):
365 if self.bottle_counter >= 3:
366 self.bottle_counter = 0
367 choice = random.choice(['MusicPlayer', 'Hat'])
368 self.game.add_thing(choice, self.position)
369 msg = 'here is a gift as a reward for ecological consciousness –'
370 if choice == 'MusicPlayer':
371 msg += 'pick it up and then use "command thing" on it!'
372 elif choice == 'Hat':
373 msg += 'pick it up and then use "(un-)wear" on it!'
374 self.sound('BOTTLE DEPOSITOR', msg)
375 # self.game.changed = True done by game.add_thing
378 self.bottle_counter += 1
379 self.sound('BOTTLE DEPOSITOR',
380 'thanks for this empty bottle – deposit %s more for a gift!' %
381 (3 - self.bottle_counter))
385 class Thing_Cookie(Thing):
389 def __init__(self, *args, **kwargs):
391 super().__init__(*args, **kwargs)
392 legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
393 self.thing_char = random.choice(list(legal_chars))
397 class Thing_CookieSpawner(Thing):
400 def accept(self, thing):
401 self.sound('OVEN', '*heat* *brrzt* here\'s a cookie!')
402 self.game.add_thing('Cookie', self.position)
406 class ThingAnimate(Thing):
410 def __init__(self, *args, **kwargs):
411 super().__init__(*args, **kwargs)
412 self.next_task = [None]
414 self.invalidate('fov')
415 self.invalidate('other') # currently redundant though
417 def invalidate(self, type_):
420 self._visible_terrain = None
421 self._visible_control = None
422 self.invalidate('other')
423 elif type_ == 'other':
424 self._seen_things = None
425 self._seen_annotation_positions = None
426 self._seen_portal_positions = None
428 def set_next_task(self, task_name, args=()):
429 task_class = self.game.tasks[task_name]
430 self.next_task = [task_class(self, args)]
432 def get_next_task(self):
433 if self.next_task[0]:
434 task = self.next_task[0]
435 self.next_task = [None]
442 for c_id in self.game.sessions:
443 if self.game.sessions[c_id]['thing_id'] == self.id_:
444 # TODO: refactor with self.send_msg
445 self.game.io.send('DEFAULT_COLORS', c_id)
446 self.game.io.send('CHAT "You sober up."', c_id)
447 self.invalidate('fov')
449 self.game.changed = True
450 if self.task is None:
451 self.task = self.get_next_task()
455 except (PlayError, GameError) as e:
459 if self.task.todo <= 0:
461 self.game.changed = True
462 self.task = self.get_next_task()
464 def prepare_multiprocessible_fov_stencil(self):
465 fov_map_class = self.game.map_geometry.fov_map_class
466 fov_radius = 3 if self.drunk > 0 else 12
467 light_blockers = self.game.get_light_blockers()
468 self._fov = fov_map_class(light_blockers, self.game.things, self.game.maps,
469 self.position, fov_radius, self.game.get_map)
471 def multiprocessible_fov_stencil(self):
472 self._fov.init_terrain()
475 def fov_stencil(self):
478 # due to the pre-multiprocessing in game.send_gamestate,
479 # the following should actually never be called
480 self.prepare_multiprocessible_fov_stencil()
481 self.multiprocessible_fov_stencil()
484 def fov_stencil_make(self):
487 def fov_test(self, big_yx, little_yx):
488 test_position = self.fov_stencil.target_yx(big_yx, little_yx)
489 if self.fov_stencil.inside(test_position):
490 if self.fov_stencil[test_position] == '.':
494 def fov_stencil_map(self, map_type):
496 for yx in self.fov_stencil:
497 if self.fov_stencil[yx] == '.':
498 big_yx, little_yx = self.fov_stencil.source_yxyx(yx)
499 map_ = self.game.get_map(big_yx, map_type)
500 visible_terrain += map_[little_yx]
502 visible_terrain += ' '
503 return visible_terrain
506 def visible_terrain(self):
507 if self._visible_terrain:
508 return self._visible_terrain
509 self._visible_terrain = self.fov_stencil_map('normal')
510 return self._visible_terrain
513 def visible_control(self):
514 if self._visible_control:
515 return self._visible_control
516 self._visible_control = self.fov_stencil_map('control')
517 return self._visible_control
520 def seen_things(self):
521 if self._seen_things is not None:
522 return self._seen_things
523 self._seen_things = [t for t in self.game.things
524 if self.fov_test(*t.position)]
525 return self._seen_things
528 def seen_annotation_positions(self):
529 if self._seen_annotation_positions is not None:
530 return self._seen_annotation_positions
531 self._seen_annotation_positions = []
532 for big_yx in self.game.annotations:
533 for little_yx in [little_yx for little_yx
534 in self.game.annotations[big_yx]
535 if self.fov_test(big_yx, little_yx)]:
536 self._seen_annotation_positions += [(big_yx, little_yx)]
537 return self._seen_annotation_positions
540 def seen_portal_positions(self):
541 if self._seen_portal_positions is not None:
542 return self._seen_portal_positions
543 self._seen_portal_positions = []
544 for big_yx in self.game.portals:
545 for little_yx in [little_yx for little_yx
546 in self.game.portals[big_yx]
547 if self.fov_test(big_yx, little_yx)]:
548 self._seen_portal_positions += [(big_yx, little_yx)]
549 return self._seen_portal_positions
553 class Thing_Player(ThingAnimate):
556 def __init__(self, *args, **kwargs):
557 super().__init__(*args, **kwargs)
560 def send_msg(self, msg):
561 for c_id in self.game.sessions:
562 if self.game.sessions[c_id]['thing_id'] == self.id_:
563 self.game.io.send(msg, c_id)
572 def add_cookie_char(self, c):
573 if not self.name in self.game.players_hat_chars:
574 self.game.players_hat_chars[self.name] = ' #' # default
575 if not c in self.game.players_hat_chars[self.name]:
576 self.game.players_hat_chars[self.name] += c
578 def get_cookie_chars(self):
579 if self.name in self.game.players_hat_chars:
580 return self.game.players_hat_chars[self.name]
581 return ' #' # default