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):
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,
52 factor = largest_audible_distance / 4
59 in_url = False if in_url else True
61 while random.random() > volume * factor:
64 elif c != '.' and c != ' ':
72 largest_audible_distance = 20
73 obstacles = [t.position for t in self.game.things if t.blocks_sound]
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):
149 blocks_movement = False
154 self.blocks_movement = False
155 self.blocks_light = False
156 self.blocks_sound = False
160 self.blocks_movement = True
161 self.blocks_light = True
162 self.blocks_sound = True
163 self.thing_char = '#'
166 self.portable = False
173 class Thing_Bottle(Thing):
181 self.thing_char = '_'
186 all_players = [t for t in self.game.things if t.type_ == 'Player']
187 # TODO: refactor with ThingPlayer.prepare_multiprocessible_fov_stencil
188 # and ThingPlayer.fov_test
189 fov_map_class = self.game.map_geometry.fov_map_class
191 light_blockers = self.game.get_light_blockers()
192 obstacles = [t.position for t in self.game.things if t.blocks_light]
193 fov = fov_map_class(light_blockers, obstacles, self.game.maps,
194 self.position, fov_radius, self.game.get_map)
197 for p in all_players:
198 test_position = fov.target_yx(p.position[0], p.position[1])
199 if fov.inside(test_position) and fov[test_position] == '.':
200 visible_players += [p]
201 if len(visible_players) == 0:
202 self.sound('BOTTLE', 'no visible players in spin range')
203 pick = random.choice(visible_players)
204 self.sound('BOTTLE', 'BOTTLE picks: ' + pick.name)
208 class Thing_BottleSpawner(ThingSpawner):
209 child_type = 'Bottle'
213 class Thing_Hat(Thing):
216 design = ' +--+ ' + ' | | ' + '======'
221 new_design += self.design[12]
222 new_design += self.design[13]
223 new_design += self.design[6]
224 new_design += self.design[7]
225 new_design += self.design[0]
226 new_design += self.design[1]
227 new_design += self.design[14]
228 new_design += self.design[15]
229 new_design += self.design[8]
230 new_design += self.design[9]
231 new_design += self.design[2]
232 new_design += self.design[3]
233 new_design += self.design[16]
234 new_design += self.design[17]
235 new_design += self.design[10]
236 new_design += self.design[11]
237 new_design += self.design[4]
238 new_design += self.design[5]
239 self.design = ''.join(new_design)
243 class Thing_HatRemixer(Thing):
246 def accept(self, hat):
249 legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
251 new_design += random.choice(list(legal_chars))
252 hat.design = new_design
253 self.sound('HAT REMIXER', 'remixing a hat …')
254 self.game.changed = True
255 self.game.record_change(self.position, 'other')
260 class Thing_MusicPlayer(Thing):
265 next_song_start = datetime.datetime.now()
269 def __init__(self, *args, **kwargs):
270 super().__init__(*args, **kwargs)
271 self.next_song_start = datetime.datetime.now()
275 if (not self.playing) or len(self.playlist) == 0:
277 if datetime.datetime.now() > self.next_song_start:
278 self.playlist_index += 1
279 if self.playlist_index == len(self.playlist):
280 self.playlist_index = 0
284 song_data = self.playlist[self.playlist_index]
285 self.next_song_start = datetime.datetime.now() +\
286 datetime.timedelta(seconds=song_data[1])
287 self.sound('MUSICPLAYER', song_data[0])
288 self.game.changed = True
290 def interpret(self, command):
292 if command == 'HELP':
293 msg_lines += ['available commands:']
294 msg_lines += ['HELP – show this help']
295 msg_lines += ['ON/OFF – toggle playback on/off']
296 msg_lines += ['REWIND – return to start of playlist']
297 msg_lines += ['LIST – list programmed songs, durations']
298 msg_lines += ['SKIP – to skip to next song']
299 msg_lines += ['REPEAT – toggle playlist repeat on/off']
300 msg_lines += ['ADD LENGTH SONG – add SONG to playlist, with LENGTH in format "minutes:seconds", i.e. something like "0:47" or "11:02"']
302 elif command == 'LIST':
303 msg_lines += ['playlist:']
305 for entry in self.playlist:
306 minutes = entry[1] // 60
307 seconds = entry[1] % 60
309 seconds = '0%s' % seconds
310 selector = 'next:' if i == self.playlist_index else ' '
311 msg_lines += ['%s %s:%s – %s' % (selector, minutes, seconds, entry[0])]
314 elif command == 'ON/OFF':
315 self.playing = False if self.playing else True
316 self.game.changed = True
321 elif command == 'REMOVE':
322 if len(self.playlist) == 0:
323 return ['playlist already empty']
324 del self.playlist[max(0, self.playlist_index)]
325 self.playlist_index -= 1
326 if self.playlist_index < -1:
327 self.playlist_index = -1
328 self.game.changed = True
329 return ['removed song']
330 elif command == 'REWIND':
331 self.playlist_index = -1
332 self.next_song_start = datetime.datetime.now()
333 self.game.changed = True
334 return ['back at start of playlist']
335 elif command == 'SKIP':
336 self.next_song_start = datetime.datetime.now()
337 self.game.changed = True
339 elif command == 'REPEAT':
340 self.repeat = False if self.repeat else True
341 self.game.changed = True
343 return ['playlist repeat turned on']
345 return ['playlist repeat turned off']
346 elif command.startswith('ADD '):
347 tokens = command.split(' ', 2)
349 return ['wrong syntax, see HELP']
350 length = tokens[1].split(':')
352 return ['wrong syntax, see HELP']
354 minutes = int(length[0])
355 seconds = int(length[1])
357 return ['wrong syntax, see HELP']
358 self.playlist += [(tokens[2], minutes * 60 + seconds)]
359 self.game.changed = True
362 return ['cannot understand command']
366 class Thing_BottleDeposit(Thing):
371 if self.bottle_counter >= 3:
372 self.bottle_counter = 0
373 choice = random.choice(['MusicPlayer', 'Hat'])
374 self.game.add_thing(choice, self.position)
375 msg = 'here is a gift as a reward for ecological consciousness –'
376 if choice == 'MusicPlayer':
377 msg += 'pick it up and then use "command thing" on it!'
378 elif choice == 'Hat':
379 msg += 'pick it up and then use "(un-)wear" on it!'
380 self.sound('BOTTLE DEPOSITOR', msg)
383 self.bottle_counter += 1
384 self.sound('BOTTLE DEPOSITOR',
385 'thanks for this empty bottle – deposit %s more for a gift!' %
386 (3 - self.bottle_counter))
390 class Thing_Cookie(Thing):
394 def __init__(self, *args, **kwargs):
396 super().__init__(*args, **kwargs)
397 legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
398 self.thing_char = random.choice(list(legal_chars))
402 class Thing_CookieSpawner(Thing):
405 def accept(self, thing):
406 self.sound('OVEN', '*heat* *brrzt* here\'s a cookie!')
407 self.game.add_thing('Cookie', self.position)
411 class ThingAnimate(Thing):
412 blocks_movement = True
415 def __init__(self, *args, **kwargs):
416 super().__init__(*args, **kwargs)
417 self.next_task = [None]
419 self.invalidate('fov')
420 self.invalidate('other') # currently redundant though
422 def invalidate(self, type_):
425 self._visible_terrain = None
426 self._visible_control = None
427 self.invalidate('other')
428 elif type_ == 'other':
429 self._seen_things = None
430 self._seen_annotation_positions = None
431 self._seen_portal_positions = None
433 def set_next_task(self, task_name, args=()):
434 task_class = self.game.tasks[task_name]
435 self.next_task = [task_class(self, args)]
437 def get_next_task(self):
438 if self.next_task[0]:
439 task = self.next_task[0]
440 self.next_task = [None]
447 for c_id in self.game.sessions:
448 if self.game.sessions[c_id]['thing_id'] == self.id_:
449 # TODO: refactor with self.send_msg
450 self.game.io.send('DEFAULT_COLORS', c_id)
451 self.game.io.send('CHAT "You sober up."', c_id)
452 self.invalidate('fov')
454 self.game.changed = True
455 if self.task is None:
456 self.task = self.get_next_task()
460 except (PlayError, GameError) as e:
464 if self.task.todo <= 0:
466 self.game.changed = True
467 self.task = self.get_next_task()
469 def prepare_multiprocessible_fov_stencil(self):
470 fov_map_class = self.game.map_geometry.fov_map_class
471 fov_radius = 3 if self.drunk > 0 else 12
472 light_blockers = self.game.get_light_blockers()
473 obstacles = [t.position for t in self.game.things if t.blocks_light]
474 self._fov = fov_map_class(light_blockers, obstacles, self.game.maps,
475 self.position, fov_radius, self.game.get_map)
477 def multiprocessible_fov_stencil(self):
478 self._fov.init_terrain()
481 def fov_stencil(self):
484 # due to the pre-multiprocessing in game.send_gamestate,
485 # the following should actually never be called
486 self.prepare_multiprocessible_fov_stencil()
487 self.multiprocessible_fov_stencil()
490 def fov_stencil_make(self):
493 def fov_test(self, big_yx, little_yx):
494 test_position = self.fov_stencil.target_yx(big_yx, little_yx)
495 if self.fov_stencil.inside(test_position):
496 if self.fov_stencil[test_position] == '.':
500 def fov_stencil_map(self, map_type):
502 for yx in self.fov_stencil:
503 if self.fov_stencil[yx] == '.':
504 big_yx, little_yx = self.fov_stencil.source_yxyx(yx)
505 map_ = self.game.get_map(big_yx, map_type)
506 visible_terrain += map_[little_yx]
508 visible_terrain += ' '
509 return visible_terrain
512 def visible_terrain(self):
513 if self._visible_terrain:
514 return self._visible_terrain
515 self._visible_terrain = self.fov_stencil_map('normal')
516 return self._visible_terrain
519 def visible_control(self):
520 if self._visible_control:
521 return self._visible_control
522 self._visible_control = self.fov_stencil_map('control')
523 return self._visible_control
526 def seen_things(self):
527 if self._seen_things is not None:
528 return self._seen_things
529 self._seen_things = [t for t in self.game.things
530 if self.fov_test(*t.position)]
531 return self._seen_things
534 def seen_annotation_positions(self):
535 if self._seen_annotation_positions is not None:
536 return self._seen_annotation_positions
537 self._seen_annotation_positions = []
538 for big_yx in self.game.annotations:
539 for little_yx in [little_yx for little_yx
540 in self.game.annotations[big_yx]
541 if self.fov_test(big_yx, little_yx)]:
542 self._seen_annotation_positions += [(big_yx, little_yx)]
543 return self._seen_annotation_positions
546 def seen_portal_positions(self):
547 if self._seen_portal_positions is not None:
548 return self._seen_portal_positions
549 self._seen_portal_positions = []
550 for big_yx in self.game.portals:
551 for little_yx in [little_yx for little_yx
552 in self.game.portals[big_yx]
553 if self.fov_test(big_yx, little_yx)]:
554 self._seen_portal_positions += [(big_yx, little_yx)]
555 return self._seen_portal_positions
559 class Thing_Player(ThingAnimate):
562 def __init__(self, *args, **kwargs):
563 super().__init__(*args, **kwargs)
566 def send_msg(self, msg):
567 for c_id in self.game.sessions:
568 if self.game.sessions[c_id]['thing_id'] == self.id_:
569 self.game.io.send(msg, c_id)
578 def add_cookie_char(self, c):
579 if not self.name in self.game.players_hat_chars:
580 self.game.players_hat_chars[self.name] = ' #' # default
581 if not c in self.game.players_hat_chars[self.name]:
582 self.game.players_hat_chars[self.name] += c
584 def get_cookie_chars(self):
585 if self.name in self.game.players_hat_chars:
586 return self.game.players_hat_chars[self.name]
587 return ' #' # default