home · contact · privacy
Overhaul MusicPlayer code.
[plomrogue2] / plomrogue / things.py
index dfb536c27f8e6f9acb49b8e5ad2d60d16c66e27e..c49b204f1c2e320036ab5cd19b4d2b330fec980c 100644 (file)
@@ -1,4 +1,4 @@
-from plomrogue.errors import GameError
+from plomrogue.errors import GameError, PlayError
 from plomrogue.mapping import YX
 
 
@@ -6,7 +6,7 @@ from plomrogue.mapping import YX
 class ThingBase:
     type_ = '?'
 
-    def __init__(self, game, id_=0, position=(YX(0,0))):
+    def __init__(self, game, id_=0, position=(YX(0, 0), YX(0, 0))):
         self.game = game
         if id_ == 0:
             self.id_ = self.game.new_thing_id()
@@ -18,6 +18,9 @@ class ThingBase:
 
 class Thing(ThingBase):
     blocking = False
+    portable = False
+    protection = '.'
+    commandable = False
 
     def __init__(self, *args, **kwargs):
         super().__init__(*args, **kwargs)
@@ -33,82 +36,336 @@ class Thing(ThingBase):
     def get_type(cls):
         return cls.__name__[len('Thing_'):]
 
+    def sound(self, name, msg):
+        from plomrogue.mapping import DijkstraMap
+        from plomrogue.misc import quote
+
+        def lower_msg_by_volume(msg, volume, largest_audible_distance):
+            import random
+            factor = largest_audible_distance / 4
+            lowered_msg = ''
+            for c in msg:
+                c = c
+                while random.random() > volume * factor:
+                    if c.isupper():
+                        c = c.lower()
+                    elif c != '.' and c != ' ':
+                        c = '.'
+                    else:
+                        c = ' '
+                lowered_msg += c
+            return lowered_msg
+
+        largest_audible_distance = 20
+        # player's don't block sound (or should they?)
+        things = [t for t in self.game.things if t.type_ != 'Player']
+        dijkstra_map = DijkstraMap(things, self.game.maps, self.position,
+                                   largest_audible_distance, self.game.get_map)
+        for c_id in self.game.sessions:
+            listener = self.game.get_player(c_id)
+            target_yx = dijkstra_map.target_yx(*listener.position, True)
+            if not target_yx:
+                continue
+            listener_distance = dijkstra_map[target_yx]
+            if listener_distance > largest_audible_distance:
+                continue
+            volume = 1 / max(1, listener_distance)
+            lowered_msg = lower_msg_by_volume(msg, volume,
+                                              largest_audible_distance)
+            lowered_nick = lower_msg_by_volume(name, volume,
+                                               largest_audible_distance)
+            self.game.io.send('CHAT ' +
+                              quote('(volume: %.2f) %s: %s' % (volume,
+                                                               lowered_nick,
+                                                               lowered_msg)),
+                              c_id)
+
 
 
 class Thing_Item(Thing):
     symbol_hint = 'i'
+    portable = True
+
+
+
+class ThingSpawner(Thing):
+    symbol_hint = 'S'
+
+    def proceed(self):
+        for t in [t for t in self.game.things
+                  if t != self and t.position == self.position]:
+            return
+        t = self.game.thing_types[self.child_type](self.game,
+                                                   position=self.position)
+        self.game.things += [t]
+        self.game.changed = True
+
+
+
+class Thing_ItemSpawner(ThingSpawner):
+    child_type = 'Item'
+
+
+
+class Thing_SpawnPointSpawner(ThingSpawner):
+    child_type = 'SpawnPoint'
+
+
+
+class Thing_SpawnPoint(Thing):
+    symbol_hint = 's'
+    portable = True
+    name = 'username'
+
+
+
+class Thing_DoorSpawner(ThingSpawner):
+    child_type = 'Door'
+
+
+
+class Thing_Door(Thing):
+    symbol_hint = 'D'
+    blocking = False
+    portable = True
+    installable = True
+
+    def open(self):
+        self.blocking = False
+        del self.thing_char
+
+    def close(self):
+        self.blocking = True
+        self.thing_char = '#'
+
+    def install(self):
+        self.portable = False
+
+    def uninstall(self):
+        self.portable = True
+
+
+
+class Thing_Bottle(Thing):
+    symbol_hint = 'B'
+    portable = True
+    full = True
+    thing_char = '~'
+
+    def empty(self):
+        self.thing_char = '_'
+        self.full = False
+
+
+
+class Thing_BottleSpawner(ThingSpawner):
+    child_type = 'Bottle'
+
 
 
+import datetime
+class Thing_MusicPlayer(Thing):
+    symbol_hint = 'R'
+    commandable = True
+    portable = True
+    repeat = True
+    next_song_start = datetime.datetime.now()
+    playlist_index = -1
+    playing = True
+
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+        self.next_song_start = datetime.datetime.now()
+        self.playlist = []
+
+    def proceed(self):
+        if (not self.playing) or len(self.playlist) == 0:
+            return
+        if datetime.datetime.now() > self.next_song_start:
+            self.playlist_index += 1
+            if self.playlist_index == len(self.playlist):
+                self.playlist_index = 0
+                if not self.repeat:
+                    self.playing = False
+                    return
+            song_data = self.playlist[self.playlist_index]
+            self.next_song_start = datetime.datetime.now() +\
+                datetime.timedelta(seconds=song_data[1])
+            self.sound('MUSICPLAYER', song_data[0])
+            self.game.changed = True
+
+    def interpret(self, command):
+        msg_lines = []
+        if command == 'HELP':
+            msg_lines += ['available commands:']
+            msg_lines += ['HELP – show this help']
+            msg_lines += ['ON/OFF – toggle playback on/off']
+            msg_lines += ['REWIND – return to start of playlist']
+            msg_lines += ['LIST – list programmed songs, durations']
+            msg_lines += ['SKIP – to skip to next song']
+            msg_lines += ['REPEAT – toggle playlist repeat on/off']
+            msg_lines += ['ADD LENGTH SONG – add SONG to playlist, with LENGTH in format "minutes:seconds", i.e. something like "0:47" or "11:02"']
+            return msg_lines
+        elif command == 'LIST':
+            msg_lines += ['playlist:']
+            i = 0
+            for entry in self.playlist:
+                minutes = entry[1] // 60
+                seconds = entry[1] % 60
+                if seconds < 10:
+                    seconds = '0%s' % seconds
+                selector = 'next:' if i == self.playlist_index else '     '
+                msg_lines += ['%s %s:%s – %s' % (selector, minutes, seconds, entry[0])]
+                i += 1
+            return msg_lines
+        elif command == 'ON/OFF':
+            self.playing = False if self.playing else True
+            self.game.changed = True
+            if self.playing:
+                return ['playing']
+            else:
+                return ['paused']
+        elif command == 'REWIND':
+            self.playlist_index = -1
+            self.next_song_start = datetime.datetime.now()
+            self.game.changed = True
+            return ['back at start of playlist']
+        elif command == 'SKIP':
+            self.next_song_start = datetime.datetime.now()
+            self.game.changed = True
+            return ['skipped']
+        elif command == 'REPEAT':
+            self.repeat = False if self.repeat else True
+            self.game.changed = True
+            if self.repeat:
+                return ['playlist repeat turned on']
+            else:
+                return ['playlist repeat turned off']
+        elif command.startswith('ADD '):
+            tokens = command.split(' ', 2)
+            if len(tokens) != 3:
+                return ['wrong syntax, see HELP']
+            length = tokens[1].split(':')
+            if len(length) != 2:
+                return ['wrong syntax, see HELP']
+            try:
+                minutes = int(length[0])
+                seconds = int(length[1])
+            except ValueError:
+                return ['wrong syntax, see HELP']
+            self.playlist += [(tokens[2], minutes * 60 + seconds)]
+            self.game.changed = True
+            return ['added']
+        else:
+            return ['cannot understand command']
+
+
+
+class Thing_BottleDeposit(Thing):
+    bottle_counter = 0
+    symbol_hint = 'O'
+
+    def proceed(self):
+        if self.bottle_counter >= 3:
+            self.bottle_counter = 0
+            t = self.game.thing_types['MusicPlayer'](self.game,
+                                                     position=self.position)
+            self.game.things += [t]
+            self.sound('BOTTLE DEPOSITOR',
+                       'here is a gift as a reward for ecological consciousness –'
+                       'use "command thing" on it to learn more!')
+            self.game.changed = True
+
+    def accept(self):
+        self.bottle_counter += 1
+        self.sound('BOTTLE DEPOSITOR',
+                   'thanks for this empty bottle – deposit %s more for a gift!' %
+                   (3 - self.bottle_counter))
 
-class Thing_Furniture(Thing):
-    symbol_hint = 'h'
 
 
 
 class ThingAnimate(Thing):
     blocking = True
+    drunk = 0
 
     def __init__(self, *args, **kwargs):
         super().__init__(*args, **kwargs)
-        self.next_tasks = []
-        self.set_task('WAIT')
+        self.next_task = [None]
+        self.task = None
         self._fov = None
 
-    def set_task(self, task_name, args=()):
-        task_class = self.game.tasks[task_name]
-        self.task = task_class(self, args)
-        self.task.check()  # will throw GameError if necessary
-
     def set_next_task(self, task_name, args=()):
         task_class = self.game.tasks[task_name]
-        self.next_tasks += [task_class(self, args)]
+        self.next_task = [task_class(self, args)]
 
     def get_next_task(self):
-        if len(self.next_tasks) > 0:
-            task = self.next_tasks.pop(0)
+        if self.next_task[0]:
+            task = self.next_task[0]
+            self.next_task = [None]
             task.check()
             return task
-        else:
-            return None
 
     def proceed(self):
+        self.drunk -= 1
+        if self.drunk == 0:
+            for c_id in self.game.sessions:
+                if self.game.sessions[c_id]['thing_id'] == self.id_:
+                    self.game.io.send('DEFAULT_COLORS', c_id)
+                    self.game.io.send('CHAT "You sober up."', c_id)
+                    break
+            self.game.changed = True
         self._fov = None
         if self.task is None:
             self.task = self.get_next_task()
             return
-
         try:
             self.task.check()
-        except GameError as e:
+        except (PlayError, GameError) as e:
             self.task = None
-            raise GameError
-            return
+            raise e
         self.task.todo -= 1
         if self.task.todo <= 0:
-            self._last_task_result = self.task.do()
+            self.task.do()
             self.game.changed = True
             self.task = self.get_next_task()
 
+    def prepare_multiprocessible_fov_stencil(self):
+        fov_map_class = self.game.map_geometry.fov_map_class
+        fov_radius = 3 if self.drunk > 0 else 12
+        self._fov = fov_map_class(self.game.things, self.game.maps,
+                                  self.position, fov_radius, self.game.get_map)
+
+    def multiprocessible_fov_stencil(self):
+        self._fov.init_terrain()
+
     @property
     def fov_stencil(self):
         if self._fov:
             return self._fov
-        fov_map_class = self.game.map_geometry.fov_map_class
-        self._fov = fov_map_class(self.game.map, self.position, 12)
+        # due to the pre-multiprocessing in game.send_gamestate,
+        # the following should actually never be called
+        self.prepare_multiprocessible_fov_stencil()
+        self.multiprocessible_fov_stencil()
         return self._fov
 
-    def fov_test(self, yx):
-        test_position = self.fov_stencil.target_yx(yx)
+    def fov_stencil_make(self):
+        self._fov.make()
+
+    def fov_test(self, big_yx, little_yx):
+        test_position = self.fov_stencil.target_yx(big_yx, little_yx)
         if self.fov_stencil.inside(test_position):
             if self.fov_stencil[test_position] == '.':
                 return True
         return False
 
-    def fov_stencil_map(self, map):
+    def fov_stencil_map(self, map_type='normal'):
         visible_terrain = ''
         for yx in self.fov_stencil:
             if self.fov_stencil[yx] == '.':
-                visible_terrain += map[self.fov_stencil.source_yx(yx)]
+                big_yx, little_yx = self.fov_stencil.source_yxyx(yx)
+                map_ = self.game.get_map(big_yx, map_type)
+                visible_terrain += map_[little_yx]
             else:
                 visible_terrain += ' '
         return visible_terrain
@@ -121,3 +378,9 @@ class Thing_Player(ThingAnimate):
     def __init__(self, *args, **kwargs):
         super().__init__(*args, **kwargs)
         self.carrying = None
+
+    def send_msg(self, msg):
+        for c_id in self.game.sessions:
+            if self.game.sessions[c_id]['thing_id'] == self.id_:
+                self.game.io.send(msg, c_id)
+                break