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