home · contact · privacy
Fix web client moving player with explorer on move button press.
[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         self.game.add_thing(self.child_type, self.position)
100         self.game.changed = True
101
102
103
104 class Thing_ItemSpawner(ThingSpawner):
105     child_type = 'Item'
106
107
108
109 class Thing_SpawnPointSpawner(ThingSpawner):
110     child_type = 'SpawnPoint'
111
112
113
114 class Thing_SpawnPoint(Thing):
115     symbol_hint = 's'
116     portable = True
117     name = 'username'
118
119
120
121 class Thing_DoorSpawner(ThingSpawner):
122     child_type = 'Door'
123
124
125
126 class Thing_Door(Thing):
127     symbol_hint = 'D'
128     blocking = False
129     portable = True
130     installable = True
131
132     def open(self):
133         self.blocking = False
134         del self.thing_char
135
136     def close(self):
137         self.blocking = True
138         self.thing_char = '#'
139
140     def install(self):
141         self.portable = False
142
143     def uninstall(self):
144         self.portable = True
145
146
147
148 class Thing_Bottle(Thing):
149     symbol_hint = 'B'
150     portable = True
151     full = True
152     thing_char = '~'
153
154     def empty(self):
155         self.thing_char = '_'
156         self.full = False
157
158
159
160 class Thing_BottleSpawner(ThingSpawner):
161     child_type = 'Bottle'
162
163
164
165 class Thing_Hat(Thing):
166     symbol_hint = 'H'
167     portable = True
168     design = ' +--+ ' + ' |  | ' + '======'
169
170
171
172 class Thing_HatRemixer(Thing):
173     symbol_hint = 'H'
174
175     def accept(self, hat):
176         import string
177         new_design = ''
178         legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
179         for i in range(18):
180             new_design += random.choice(list(legal_chars))
181         hat.design = new_design
182         self.sound('HAT REMIXER', 'remixing a hat …')
183         self.game.changed = True
184
185
186
187 import datetime
188 class Thing_MusicPlayer(Thing):
189     symbol_hint = 'R'
190     commandable = True
191     portable = True
192     repeat = True
193     next_song_start = datetime.datetime.now()
194     playlist_index = -1
195     playing = True
196
197     def __init__(self, *args, **kwargs):
198         super().__init__(*args, **kwargs)
199         self.next_song_start = datetime.datetime.now()
200         self.playlist = []
201
202     def proceed(self):
203         if (not self.playing) or len(self.playlist) == 0:
204             return
205         if datetime.datetime.now() > self.next_song_start:
206             self.playlist_index += 1
207             if self.playlist_index == len(self.playlist):
208                 self.playlist_index = 0
209                 if not self.repeat:
210                     self.playing = False
211                     return
212             song_data = self.playlist[self.playlist_index]
213             self.next_song_start = datetime.datetime.now() +\
214                 datetime.timedelta(seconds=song_data[1])
215             self.sound('MUSICPLAYER', song_data[0])
216             self.game.changed = True
217
218     def interpret(self, command):
219         msg_lines = []
220         if command == 'HELP':
221             msg_lines += ['available commands:']
222             msg_lines += ['HELP – show this help']
223             msg_lines += ['ON/OFF – toggle playback on/off']
224             msg_lines += ['REWIND – return to start of playlist']
225             msg_lines += ['LIST – list programmed songs, durations']
226             msg_lines += ['SKIP – to skip to next song']
227             msg_lines += ['REPEAT – toggle playlist repeat on/off']
228             msg_lines += ['ADD LENGTH SONG – add SONG to playlist, with LENGTH in format "minutes:seconds", i.e. something like "0:47" or "11:02"']
229             return msg_lines
230         elif command == 'LIST':
231             msg_lines += ['playlist:']
232             i = 0
233             for entry in self.playlist:
234                 minutes = entry[1] // 60
235                 seconds = entry[1] % 60
236                 if seconds < 10:
237                     seconds = '0%s' % seconds
238                 selector = 'next:' if i == self.playlist_index else '     '
239                 msg_lines += ['%s %s:%s – %s' % (selector, minutes, seconds, entry[0])]
240                 i += 1
241             return msg_lines
242         elif command == 'ON/OFF':
243             self.playing = False if self.playing else True
244             self.game.changed = True
245             if self.playing:
246                 return ['playing']
247             else:
248                 return ['paused']
249         elif command == 'REMOVE':
250             if len(self.playlist) == 0:
251                 return ['playlist already empty']
252             del self.playlist[max(0, self.playlist_index)]
253             self.playlist_index -= 1
254             if self.playlist_index < -1:
255                 self.playlist_index = -1
256             self.game.changed = True
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             self.game.add_thing(choice, self.position)
303             msg = 'here is a gift as a reward for ecological consciousness –'
304             if choice == 'MusicPlayer':
305                 msg += 'pick it up and then use "command thing" on it!'
306             elif choice == 'Hat':
307                 msg += 'pick it up and then use "(un-)wear" on it!'
308             self.sound('BOTTLE DEPOSITOR', msg)
309             self.game.changed = True
310
311     def accept(self):
312         self.bottle_counter += 1
313         self.sound('BOTTLE DEPOSITOR',
314                    'thanks for this empty bottle – deposit %s more for a gift!' %
315                    (3 - self.bottle_counter))
316
317
318
319
320 class ThingAnimate(Thing):
321     blocking = True
322     drunk = 0
323
324     def __init__(self, *args, **kwargs):
325         super().__init__(*args, **kwargs)
326         self.next_task = [None]
327         self.task = None
328         self.invalidate_map_view()
329
330     def invalidate_map_view(self):
331         self._fov = None
332         self._visible_terrain = None
333         self._visible_control = None
334
335     def set_next_task(self, task_name, args=()):
336         task_class = self.game.tasks[task_name]
337         self.next_task = [task_class(self, args)]
338
339     def get_next_task(self):
340         if self.next_task[0]:
341             task = self.next_task[0]
342             self.next_task = [None]
343             task.check()
344             return task
345
346     def proceed(self):
347         self.drunk -= 1
348         if self.drunk == 0:
349             for c_id in self.game.sessions:
350                 if self.game.sessions[c_id]['thing_id'] == self.id_:
351                     # TODO: refactor with self.send_msg
352                     self.game.io.send('DEFAULT_COLORS', c_id)
353                     self.game.io.send('CHAT "You sober up."', c_id)
354                     self.invalidate_map_view()
355                     break
356             self.game.changed = True
357         if self.task is None:
358             self.task = self.get_next_task()
359             return
360         try:
361             self.task.check()
362         except (PlayError, GameError) as e:
363             self.task = None
364             raise e
365         self.task.todo -= 1
366         if self.task.todo <= 0:
367             self.task.do()
368             self.game.changed = True
369             self.task = self.get_next_task()
370
371     def prepare_multiprocessible_fov_stencil(self):
372         fov_map_class = self.game.map_geometry.fov_map_class
373         fov_radius = 3 if self.drunk > 0 else 12
374         self._fov = fov_map_class(self.game.things, self.game.maps,
375                                   self.position, fov_radius, self.game.get_map)
376
377     def multiprocessible_fov_stencil(self):
378         self._fov.init_terrain()
379
380     @property
381     def fov_stencil(self):
382         if self._fov:
383             return self._fov
384         # due to the pre-multiprocessing in game.send_gamestate,
385         # the following should actually never be called
386         self.prepare_multiprocessible_fov_stencil()
387         self.multiprocessible_fov_stencil()
388         return self._fov
389
390     def fov_stencil_make(self):
391         self._fov.make()
392
393     def fov_test(self, big_yx, little_yx):
394         test_position = self.fov_stencil.target_yx(big_yx, little_yx)
395         if self.fov_stencil.inside(test_position):
396             if self.fov_stencil[test_position] == '.':
397                 return True
398         return False
399
400     def fov_stencil_map(self, map_type):
401         visible_terrain = ''
402         for yx in self.fov_stencil:
403             if self.fov_stencil[yx] == '.':
404                 big_yx, little_yx = self.fov_stencil.source_yxyx(yx)
405                 map_ = self.game.get_map(big_yx, map_type)
406                 visible_terrain += map_[little_yx]
407             else:
408                 visible_terrain += ' '
409         return visible_terrain
410
411     @property
412     def visible_terrain(self):
413         if self._visible_terrain:
414             return self._visible_terrain
415         self._visible_terrain = self.fov_stencil_map('normal')
416         return self._visible_terrain
417
418     @property
419     def visible_control(self):
420         if self._visible_control:
421             return self._visible_control
422         self._visible_control = self.fov_stencil_map('control')
423         return self._visible_control
424
425
426
427 class Thing_Player(ThingAnimate):
428     symbol_hint = '@'
429
430     def __init__(self, *args, **kwargs):
431         super().__init__(*args, **kwargs)
432         self.carrying = None
433
434     def send_msg(self, msg):
435         for c_id in self.game.sessions:
436             if self.game.sessions[c_id]['thing_id'] == self.id_:
437                 self.game.io.send(msg, c_id)
438                 break