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