home · contact · privacy
In pick_up selection view, use list indexes instead of internal .id_.
[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
132     def open(self):
133         self.blocking = False
134         self.portable = True
135         del self.thing_char
136
137     def close(self):
138         self.blocking = True
139         self.portable = False
140         self.thing_char = '#'
141
142
143
144 class Thing_Bottle(Thing):
145     symbol_hint = 'B'
146     portable = True
147     full = True
148     thing_char = '~'
149
150     def empty(self):
151         self.thing_char = '_'
152         self.full = False
153
154
155
156 class Thing_BottleSpawner(ThingSpawner):
157     child_type = 'Bottle'
158
159
160
161 import datetime
162 class Thing_MusicPlayer(Thing):
163     symbol_hint = 'R'
164     commandable = True
165     portable = True
166     repeat = True
167     next_song_start = datetime.datetime.now()
168     playlist_index = 0
169     playing = True
170
171     def __init__(self, *args, **kwargs):
172         super().__init__(*args, **kwargs)
173         self.next_song_start = datetime.datetime.now()
174         self.playlist = []
175
176     def proceed(self):
177         if (not self.playing) or len(self.playlist) == 0:
178             return
179         if datetime.datetime.now() > self.next_song_start:
180             song_data = self.playlist[self.playlist_index]
181             self.playlist_index += 1
182             if self.playlist_index == len(self.playlist):
183                 self.playlist_index = 0
184                 if not self.repeat:
185                     self.playing = False
186             self.next_song_start = datetime.datetime.now() +\
187                 datetime.timedelta(seconds=song_data[1])
188             self.sound('MUSICPLAYER', song_data[0])
189             self.game.changed = True
190
191     def interpret(self, command):
192         if command == 'HELP':
193             msg = 'available commands:\n'
194             msg += 'HELP – show this help\n'
195             msg += 'PLAY – toggle playback on/off\n'
196             msg += 'REWIND – return to start of playlist\n'
197             msg += 'LIST – list programmed songs, durations\n'
198             msg += 'SKIP – to skip to next song\n'
199             msg += 'REPEAT – toggle playlist repeat on/off\n'
200             msg += 'ADD LENGTH SONG – add SONG to playlist, with LENGTH in format "minutes:seconds", i.e. something like "0:47" or "11:02"'
201             return msg
202         elif command == 'LIST':
203             msg = 'playlist:'
204             i = 0
205             for entry in self.playlist:
206                 msg += '\n'
207                 minutes = entry[1] // 60
208                 seconds = entry[1] % 60
209                 if seconds < 10:
210                     seconds = '0%s' % seconds
211                 selector = 'next:' if i == self.playlist_index else '     '
212                 msg += '%s %s:%s – %s' % (selector, minutes, seconds, entry[0])
213                 i += 1
214             return msg
215         elif command == 'PLAY':
216             self.playing = False if self.playing else True
217             self.game.changed = True
218             if self.playing:
219                 return 'playing'
220             else:
221                 return 'paused'
222         elif command == 'REWIND':
223             self.playlist_index = 0
224             self.next_song_start = datetime.datetime.now()
225             self.game.changed = True
226             return 'back at start of playlist'
227         elif command == 'SKIP':
228             self.next_song_start = datetime.datetime.now()
229             self.game.changed = True
230             return 'skipped'
231         elif command == 'REPEAT':
232             self.repeat = False if self.repeat else True
233             self.game.changed = True
234             if self.repeat:
235                 return 'playlist repeat turned on'
236             else:
237                 return 'playlist repeat turned off'
238         elif command.startswith('ADD '):
239             tokens = command.split(' ', 2)
240             if len(tokens) != 3:
241                 return 'wrong syntax, see HELP'
242             length = tokens[1].split(':')
243             if len(length) != 2:
244                 return 'wrong syntax, see HELP'
245             try:
246                 minutes = int(length[0])
247                 seconds = int(length[1])
248             except ValueError:
249                 return 'wrong syntax, see HELP'
250             self.playlist += [(tokens[2], minutes * 60 + seconds)]
251             self.game.changed = True
252             return 'added'
253         else:
254             return 'cannot understand command'
255
256
257
258 class Thing_BottleDeposit(Thing):
259     bottle_counter = 0
260     symbol_hint = 'O'
261
262     def proceed(self):
263         if self.bottle_counter >= 3:
264             self.bottle_counter = 0
265             t = self.game.thing_types['MusicPlayer'](self.game,
266                                                      position=self.position)
267             self.game.things += [t]
268             self.sound('BOTTLE DEPOSITOR',
269                        'here is a gift as a reward for ecological consciousness –'
270                        'use "command thing" on it to learn more!')
271             self.game.changed = True
272
273     def accept(self):
274         self.bottle_counter += 1
275         self.sound('BOTTLE DEPOSITOR',
276                    'thanks for this empty bottle – deposit %s more for a gift!' %
277                    (3 - self.bottle_counter))
278
279
280
281
282 class ThingAnimate(Thing):
283     blocking = True
284     drunk = 0
285
286     def __init__(self, *args, **kwargs):
287         super().__init__(*args, **kwargs)
288         self.next_task = [None]
289         self.task = None
290         self._fov = None
291
292     def set_next_task(self, task_name, args=()):
293         task_class = self.game.tasks[task_name]
294         self.next_task = [task_class(self, args)]
295
296     def get_next_task(self):
297         if self.next_task[0]:
298             task = self.next_task[0]
299             self.next_task = [None]
300             task.check()
301             return task
302
303     def proceed(self):
304         self.drunk -= 1
305         if self.drunk == 0:
306             for c_id in self.game.sessions:
307                 if self.game.sessions[c_id]['thing_id'] == self.id_:
308                     self.game.io.send('DEFAULT_COLORS', c_id)
309                     self.game.io.send('CHAT "You sober up."', c_id)
310                     break
311             self.game.changed = True
312         self._fov = None
313         if self.task is None:
314             self.task = self.get_next_task()
315             return
316         try:
317             self.task.check()
318         except (PlayError, GameError) as e:
319             self.task = None
320             raise e
321         self.task.todo -= 1
322         if self.task.todo <= 0:
323             self.task.do()
324             self.game.changed = True
325             self.task = self.get_next_task()
326
327     def prepare_multiprocessible_fov_stencil(self):
328         fov_map_class = self.game.map_geometry.fov_map_class
329         fov_radius = 3 if self.drunk > 0 else 12
330         self._fov = fov_map_class(self.game.things, self.game.maps,
331                                   self.position, fov_radius, self.game.get_map)
332
333     def multiprocessible_fov_stencil(self):
334         self._fov.init_terrain()
335
336     @property
337     def fov_stencil(self):
338         if self._fov:
339             return self._fov
340         # due to the pre-multiprocessing in game.send_gamestate,
341         # the following should actually never be called
342         self.prepare_multiprocessible_fov_stencil()
343         self.multiprocessible_fov_stencil()
344         return self._fov
345
346     def fov_stencil_make(self):
347         self._fov.make()
348
349     def fov_test(self, big_yx, little_yx):
350         test_position = self.fov_stencil.target_yx(big_yx, little_yx)
351         if self.fov_stencil.inside(test_position):
352             if self.fov_stencil[test_position] == '.':
353                 return True
354         return False
355
356     def fov_stencil_map(self, map_type='normal'):
357         visible_terrain = ''
358         for yx in self.fov_stencil:
359             if self.fov_stencil[yx] == '.':
360                 big_yx, little_yx = self.fov_stencil.source_yxyx(yx)
361                 map_ = self.game.get_map(big_yx, map_type)
362                 visible_terrain += map_[little_yx]
363             else:
364                 visible_terrain += ' '
365         return visible_terrain
366
367
368
369 class Thing_Player(ThingAnimate):
370     symbol_hint = '@'
371
372     def __init__(self, *args, **kwargs):
373         super().__init__(*args, **kwargs)
374         self.carrying = None