home · contact · privacy
Fix remixer drop bug.
[plomrogue2] / plomrogue / things.py
1 from plomrogue.errors import GameError, PlayError
2 from plomrogue.mapping import YX
3 import random
4
5
6
7 class ThingBase:
8     type_ = '?'
9
10     def __init__(self, game, id_=0, position=(YX(0, 0), YX(0, 0))):
11         self.game = game
12         if id_ == 0:
13             self.id_ = self.game.new_thing_id()
14         else:
15             self.id_ = id_
16         self.position = position
17
18
19
20 class Thing(ThingBase):
21     blocking = False
22     portable = False
23     protection = '.'
24     commandable = False
25
26     def __init__(self, *args, **kwargs):
27         super().__init__(*args, **kwargs)
28
29     def proceed(self):
30         pass
31
32     @property
33     def type_(self):
34         return self.__class__.get_type()
35
36     @classmethod
37     def get_type(cls):
38         return cls.__name__[len('Thing_'):]
39
40     def sound(self, name, msg):
41         from plomrogue.mapping import DijkstraMap
42         from plomrogue.misc import quote
43
44         def lower_msg_by_volume(msg, volume, largest_audible_distance):
45             import random
46             factor = largest_audible_distance / 4
47             lowered_msg = ''
48             for c in msg:
49                 c = c
50                 while random.random() > volume * factor:
51                     if c.isupper():
52                         c = c.lower()
53                     elif c != '.' and c != ' ':
54                         c = '.'
55                     else:
56                         c = ' '
57                 lowered_msg += c
58             return lowered_msg
59
60         largest_audible_distance = 20
61         # player's don't block sound (or should they?)
62         things = [t for t in self.game.things if t.type_ != 'Player']
63         dijkstra_map = DijkstraMap(things, self.game.maps, self.position,
64                                    largest_audible_distance, self.game.get_map)
65         for c_id in self.game.sessions:
66             listener = self.game.get_player(c_id)
67             target_yx = dijkstra_map.target_yx(*listener.position, True)
68             if not target_yx:
69                 continue
70             listener_distance = dijkstra_map[target_yx]
71             if listener_distance > largest_audible_distance:
72                 continue
73             volume = 1 / max(1, listener_distance)
74             lowered_msg = lower_msg_by_volume(msg, volume,
75                                               largest_audible_distance)
76             lowered_nick = lower_msg_by_volume(name, volume,
77                                                largest_audible_distance)
78             self.game.io.send('CHAT ' +
79                               quote('(volume: %.2f) %s: %s' % (volume,
80                                                                lowered_nick,
81                                                                lowered_msg)),
82                               c_id)
83
84
85
86 class Thing_Item(Thing):
87     symbol_hint = 'i'
88     portable = True
89
90
91
92 class ThingSpawner(Thing):
93     symbol_hint = 'S'
94
95     def proceed(self):
96         for t in [t for t in self.game.things
97                   if t != self and t.position == self.position]:
98             return
99         t = self.game.thing_types[self.child_type](self.game,
100                                                    position=self.position)
101         self.game.things += [t]
102         self.game.changed = True
103
104
105
106 class Thing_ItemSpawner(ThingSpawner):
107     child_type = 'Item'
108
109
110
111 class Thing_SpawnPointSpawner(ThingSpawner):
112     child_type = 'SpawnPoint'
113
114
115
116 class Thing_SpawnPoint(Thing):
117     symbol_hint = 's'
118     portable = True
119     name = 'username'
120
121
122
123 class Thing_DoorSpawner(ThingSpawner):
124     child_type = 'Door'
125
126
127
128 class Thing_Door(Thing):
129     symbol_hint = 'D'
130     blocking = False
131     portable = True
132     installable = True
133
134     def open(self):
135         self.blocking = False
136         del self.thing_char
137
138     def close(self):
139         self.blocking = True
140         self.thing_char = '#'
141
142     def install(self):
143         self.portable = False
144
145     def uninstall(self):
146         self.portable = True
147
148
149
150 class Thing_Bottle(Thing):
151     symbol_hint = 'B'
152     portable = True
153     full = True
154     thing_char = '~'
155
156     def empty(self):
157         self.thing_char = '_'
158         self.full = False
159
160
161
162 class Thing_BottleSpawner(ThingSpawner):
163     child_type = 'Bottle'
164
165
166
167 class Thing_Hat(Thing):
168     symbol_hint = 'H'
169     portable = True
170     design = ' +--+ ' + ' |  | ' + '======'
171
172
173
174 class Thing_HatRemixer(Thing):
175     symbol_hint = 'H'
176
177     def accept(self, hat):
178         import string
179         new_design = ''
180         legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
181         for i in range(18):
182             new_design += random.choice(list(legal_chars))
183         hat.design = new_design
184         self.sound('HAT REMIXER', 'remixing a hat …')
185         self.game.changed = True
186
187
188
189 import datetime
190 class Thing_MusicPlayer(Thing):
191     symbol_hint = 'R'
192     commandable = True
193     portable = True
194     repeat = True
195     next_song_start = datetime.datetime.now()
196     playlist_index = -1
197     playing = True
198
199     def __init__(self, *args, **kwargs):
200         super().__init__(*args, **kwargs)
201         self.next_song_start = datetime.datetime.now()
202         self.playlist = []
203
204     def proceed(self):
205         if (not self.playing) or len(self.playlist) == 0:
206             return
207         if datetime.datetime.now() > self.next_song_start:
208             self.playlist_index += 1
209             if self.playlist_index == len(self.playlist):
210                 self.playlist_index = 0
211                 if not self.repeat:
212                     self.playing = False
213                     return
214             song_data = self.playlist[self.playlist_index]
215             self.next_song_start = datetime.datetime.now() +\
216                 datetime.timedelta(seconds=song_data[1])
217             self.sound('MUSICPLAYER', song_data[0])
218             self.game.changed = True
219
220     def interpret(self, command):
221         msg_lines = []
222         if command == 'HELP':
223             msg_lines += ['available commands:']
224             msg_lines += ['HELP – show this help']
225             msg_lines += ['ON/OFF – toggle playback on/off']
226             msg_lines += ['REWIND – return to start of playlist']
227             msg_lines += ['LIST – list programmed songs, durations']
228             msg_lines += ['SKIP – to skip to next song']
229             msg_lines += ['REPEAT – toggle playlist repeat on/off']
230             msg_lines += ['ADD LENGTH SONG – add SONG to playlist, with LENGTH in format "minutes:seconds", i.e. something like "0:47" or "11:02"']
231             return msg_lines
232         elif command == 'LIST':
233             msg_lines += ['playlist:']
234             i = 0
235             for entry in self.playlist:
236                 minutes = entry[1] // 60
237                 seconds = entry[1] % 60
238                 if seconds < 10:
239                     seconds = '0%s' % seconds
240                 selector = 'next:' if i == self.playlist_index else '     '
241                 msg_lines += ['%s %s:%s – %s' % (selector, minutes, seconds, entry[0])]
242                 i += 1
243             return msg_lines
244         elif command == 'ON/OFF':
245             self.playing = False if self.playing else True
246             self.game.changed = True
247             if self.playing:
248                 return ['playing']
249             else:
250                 return ['paused']
251         elif command == 'REMOVE':
252             if len(self.playlist) == 0:
253                 return ['playlist already empty']
254             del self.playlist[max(0, self.playlist_index)]
255             self.playlist_index -= 1
256             if self.playlist_index < -1:
257                 self.playlist_index = -1
258             return ['removed song']
259         elif command == 'REWIND':
260             self.playlist_index = -1
261             self.next_song_start = datetime.datetime.now()
262             self.game.changed = True
263             return ['back at start of playlist']
264         elif command == 'SKIP':
265             self.next_song_start = datetime.datetime.now()
266             self.game.changed = True
267             return ['skipped']
268         elif command == 'REPEAT':
269             self.repeat = False if self.repeat else True
270             self.game.changed = True
271             if self.repeat:
272                 return ['playlist repeat turned on']
273             else:
274                 return ['playlist repeat turned off']
275         elif command.startswith('ADD '):
276             tokens = command.split(' ', 2)
277             if len(tokens) != 3:
278                 return ['wrong syntax, see HELP']
279             length = tokens[1].split(':')
280             if len(length) != 2:
281                 return ['wrong syntax, see HELP']
282             try:
283                 minutes = int(length[0])
284                 seconds = int(length[1])
285             except ValueError:
286                 return ['wrong syntax, see HELP']
287             self.playlist += [(tokens[2], minutes * 60 + seconds)]
288             self.game.changed = True
289             return ['added']
290         else:
291             return ['cannot understand command']
292
293
294
295 class Thing_BottleDeposit(Thing):
296     bottle_counter = 0
297     symbol_hint = 'O'
298
299     def proceed(self):
300         if self.bottle_counter >= 3:
301             self.bottle_counter = 0
302             choice = random.choice(['MusicPlayer', 'Hat'])
303             t = self.game.thing_types[choice](self.game, position=self.position)
304             self.game.things += [t]
305             msg = 'here is a gift as a reward for ecological consciousness –'
306             if choice == 'MusicPlayer':
307                 msg += 'pick it up and then use "command thing" on it!'
308             elif choice == 'Hat':
309                 msg += 'pick it up and then use "(un-)wear" on it!'
310             self.sound('BOTTLE DEPOSITOR', msg)
311             self.game.changed = True
312
313     def accept(self):
314         self.bottle_counter += 1
315         self.sound('BOTTLE DEPOSITOR',
316                    'thanks for this empty bottle – deposit %s more for a gift!' %
317                    (3 - self.bottle_counter))
318
319
320
321
322 class ThingAnimate(Thing):
323     blocking = True
324     drunk = 0
325
326     def __init__(self, *args, **kwargs):
327         super().__init__(*args, **kwargs)
328         self.next_task = [None]
329         self.task = None
330         self._fov = None
331
332     def set_next_task(self, task_name, args=()):
333         task_class = self.game.tasks[task_name]
334         self.next_task = [task_class(self, args)]
335
336     def get_next_task(self):
337         if self.next_task[0]:
338             task = self.next_task[0]
339             self.next_task = [None]
340             task.check()
341             return task
342
343     def proceed(self):
344         self.drunk -= 1
345         if self.drunk == 0:
346             for c_id in self.game.sessions:
347                 if self.game.sessions[c_id]['thing_id'] == self.id_:
348                     self.game.io.send('DEFAULT_COLORS', c_id)
349                     self.game.io.send('CHAT "You sober up."', c_id)
350                     break
351             self.game.changed = True
352         self._fov = None
353         if self.task is None:
354             self.task = self.get_next_task()
355             return
356         try:
357             self.task.check()
358         except (PlayError, GameError) as e:
359             self.task = None
360             raise e
361         self.task.todo -= 1
362         if self.task.todo <= 0:
363             self.task.do()
364             self.game.changed = True
365             self.task = self.get_next_task()
366
367     def prepare_multiprocessible_fov_stencil(self):
368         fov_map_class = self.game.map_geometry.fov_map_class
369         fov_radius = 3 if self.drunk > 0 else 12
370         self._fov = fov_map_class(self.game.things, self.game.maps,
371                                   self.position, fov_radius, self.game.get_map)
372
373     def multiprocessible_fov_stencil(self):
374         self._fov.init_terrain()
375
376     @property
377     def fov_stencil(self):
378         if self._fov:
379             return self._fov
380         # due to the pre-multiprocessing in game.send_gamestate,
381         # the following should actually never be called
382         self.prepare_multiprocessible_fov_stencil()
383         self.multiprocessible_fov_stencil()
384         return self._fov
385
386     def fov_stencil_make(self):
387         self._fov.make()
388
389     def fov_test(self, big_yx, little_yx):
390         test_position = self.fov_stencil.target_yx(big_yx, little_yx)
391         if self.fov_stencil.inside(test_position):
392             if self.fov_stencil[test_position] == '.':
393                 return True
394         return False
395
396     def fov_stencil_map(self, map_type='normal'):
397         visible_terrain = ''
398         for yx in self.fov_stencil:
399             if self.fov_stencil[yx] == '.':
400                 big_yx, little_yx = self.fov_stencil.source_yxyx(yx)
401                 map_ = self.game.get_map(big_yx, map_type)
402                 visible_terrain += map_[little_yx]
403             else:
404                 visible_terrain += ' '
405         return visible_terrain
406
407
408
409 class Thing_Player(ThingAnimate):
410     symbol_hint = '@'
411
412     def __init__(self, *args, **kwargs):
413         super().__init__(*args, **kwargs)
414         self.carrying = None
415
416     def send_msg(self, msg):
417         for c_id in self.game.sessions:
418             if self.game.sessions[c_id]['thing_id'] == self.id_:
419                 self.game.io.send(msg, c_id)
420                 break