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