home · contact · privacy
Widen face and hat.
[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
186
187
188 import datetime
189 class Thing_MusicPlayer(Thing):
190     symbol_hint = 'R'
191     commandable = True
192     portable = True
193     repeat = True
194     next_song_start = datetime.datetime.now()
195     playlist_index = -1
196     playing = True
197
198     def __init__(self, *args, **kwargs):
199         super().__init__(*args, **kwargs)
200         self.next_song_start = datetime.datetime.now()
201         self.playlist = []
202
203     def proceed(self):
204         if (not self.playing) or len(self.playlist) == 0:
205             return
206         if datetime.datetime.now() > self.next_song_start:
207             self.playlist_index += 1
208             if self.playlist_index == len(self.playlist):
209                 self.playlist_index = 0
210                 if not self.repeat:
211                     self.playing = False
212                     return
213             song_data = self.playlist[self.playlist_index]
214             self.next_song_start = datetime.datetime.now() +\
215                 datetime.timedelta(seconds=song_data[1])
216             self.sound('MUSICPLAYER', song_data[0])
217             self.game.changed = True
218
219     def interpret(self, command):
220         msg_lines = []
221         if command == 'HELP':
222             msg_lines += ['available commands:']
223             msg_lines += ['HELP – show this help']
224             msg_lines += ['ON/OFF – toggle playback on/off']
225             msg_lines += ['REWIND – return to start of playlist']
226             msg_lines += ['LIST – list programmed songs, durations']
227             msg_lines += ['SKIP – to skip to next song']
228             msg_lines += ['REPEAT – toggle playlist repeat on/off']
229             msg_lines += ['ADD LENGTH SONG – add SONG to playlist, with LENGTH in format "minutes:seconds", i.e. something like "0:47" or "11:02"']
230             return msg_lines
231         elif command == 'LIST':
232             msg_lines += ['playlist:']
233             i = 0
234             for entry in self.playlist:
235                 minutes = entry[1] // 60
236                 seconds = entry[1] % 60
237                 if seconds < 10:
238                     seconds = '0%s' % seconds
239                 selector = 'next:' if i == self.playlist_index else '     '
240                 msg_lines += ['%s %s:%s – %s' % (selector, minutes, seconds, entry[0])]
241                 i += 1
242             return msg_lines
243         elif command == 'ON/OFF':
244             self.playing = False if self.playing else True
245             self.game.changed = True
246             if self.playing:
247                 return ['playing']
248             else:
249                 return ['paused']
250         elif command == 'REMOVE':
251             if len(self.playlist) == 0:
252                 return ['playlist already empty']
253             del self.playlist[max(0, self.playlist_index)]
254             self.playlist_index -= 1
255             if self.playlist_index < -1:
256                 self.playlist_index = -1
257             return ['removed song']
258         elif command == 'REWIND':
259             self.playlist_index = -1
260             self.next_song_start = datetime.datetime.now()
261             self.game.changed = True
262             return ['back at start of playlist']
263         elif command == 'SKIP':
264             self.next_song_start = datetime.datetime.now()
265             self.game.changed = True
266             return ['skipped']
267         elif command == 'REPEAT':
268             self.repeat = False if self.repeat else True
269             self.game.changed = True
270             if self.repeat:
271                 return ['playlist repeat turned on']
272             else:
273                 return ['playlist repeat turned off']
274         elif command.startswith('ADD '):
275             tokens = command.split(' ', 2)
276             if len(tokens) != 3:
277                 return ['wrong syntax, see HELP']
278             length = tokens[1].split(':')
279             if len(length) != 2:
280                 return ['wrong syntax, see HELP']
281             try:
282                 minutes = int(length[0])
283                 seconds = int(length[1])
284             except ValueError:
285                 return ['wrong syntax, see HELP']
286             self.playlist += [(tokens[2], minutes * 60 + seconds)]
287             self.game.changed = True
288             return ['added']
289         else:
290             return ['cannot understand command']
291
292
293
294 class Thing_BottleDeposit(Thing):
295     bottle_counter = 0
296     symbol_hint = 'O'
297
298     def proceed(self):
299         if self.bottle_counter >= 3:
300             self.bottle_counter = 0
301             choice = random.choice(['MusicPlayer', 'Hat'])
302             t = self.game.thing_types[choice](self.game, position=self.position)
303             self.game.things += [t]
304             msg = 'here is a gift as a reward for ecological consciousness –'
305             if choice == 'MusicPlayer':
306                 msg += 'pick it up and then use "command thing" on it!'
307             elif choice == 'Hat':
308                 msg += 'pick it up and then use "(un-)wear" on it!'
309             self.sound('BOTTLE DEPOSITOR', msg)
310             self.game.changed = True
311
312     def accept(self):
313         self.bottle_counter += 1
314         self.sound('BOTTLE DEPOSITOR',
315                    'thanks for this empty bottle – deposit %s more for a gift!' %
316                    (3 - self.bottle_counter))
317
318
319
320
321 class ThingAnimate(Thing):
322     blocking = True
323     drunk = 0
324
325     def __init__(self, *args, **kwargs):
326         super().__init__(*args, **kwargs)
327         self.next_task = [None]
328         self.task = None
329         self._fov = None
330
331     def set_next_task(self, task_name, args=()):
332         task_class = self.game.tasks[task_name]
333         self.next_task = [task_class(self, args)]
334
335     def get_next_task(self):
336         if self.next_task[0]:
337             task = self.next_task[0]
338             self.next_task = [None]
339             task.check()
340             return task
341
342     def proceed(self):
343         self.drunk -= 1
344         if self.drunk == 0:
345             for c_id in self.game.sessions:
346                 if self.game.sessions[c_id]['thing_id'] == self.id_:
347                     self.game.io.send('DEFAULT_COLORS', c_id)
348                     self.game.io.send('CHAT "You sober up."', c_id)
349                     break
350             self.game.changed = True
351         self._fov = None
352         if self.task is None:
353             self.task = self.get_next_task()
354             return
355         try:
356             self.task.check()
357         except (PlayError, GameError) as e:
358             self.task = None
359             raise e
360         self.task.todo -= 1
361         if self.task.todo <= 0:
362             self.task.do()
363             self.game.changed = True
364             self.task = self.get_next_task()
365
366     def prepare_multiprocessible_fov_stencil(self):
367         fov_map_class = self.game.map_geometry.fov_map_class
368         fov_radius = 3 if self.drunk > 0 else 12
369         self._fov = fov_map_class(self.game.things, self.game.maps,
370                                   self.position, fov_radius, self.game.get_map)
371
372     def multiprocessible_fov_stencil(self):
373         self._fov.init_terrain()
374
375     @property
376     def fov_stencil(self):
377         if self._fov:
378             return self._fov
379         # due to the pre-multiprocessing in game.send_gamestate,
380         # the following should actually never be called
381         self.prepare_multiprocessible_fov_stencil()
382         self.multiprocessible_fov_stencil()
383         return self._fov
384
385     def fov_stencil_make(self):
386         self._fov.make()
387
388     def fov_test(self, big_yx, little_yx):
389         test_position = self.fov_stencil.target_yx(big_yx, little_yx)
390         if self.fov_stencil.inside(test_position):
391             if self.fov_stencil[test_position] == '.':
392                 return True
393         return False
394
395     def fov_stencil_map(self, map_type='normal'):
396         visible_terrain = ''
397         for yx in self.fov_stencil:
398             if self.fov_stencil[yx] == '.':
399                 big_yx, little_yx = self.fov_stencil.source_yxyx(yx)
400                 map_ = self.game.get_map(big_yx, map_type)
401                 visible_terrain += map_[little_yx]
402             else:
403                 visible_terrain += ' '
404         return visible_terrain
405
406
407
408 class Thing_Player(ThingAnimate):
409     symbol_hint = '@'
410
411     def __init__(self, *args, **kwargs):
412         super().__init__(*args, **kwargs)
413         self.carrying = None
414
415     def send_msg(self, msg):
416         for c_id in self.game.sessions:
417             if self.game.sessions[c_id]['thing_id'] == self.id_:
418                 self.game.io.send(msg, c_id)
419                 break