home · contact · privacy
Disallow picking up thing already carried by other player.
[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     carried = False
26
27     def __init__(self, *args, **kwargs):
28         super().__init__(*args, **kwargs)
29
30     def proceed(self):
31         pass
32
33     @property
34     def type_(self):
35         return self.__class__.get_type()
36
37     @classmethod
38     def get_type(cls):
39         return cls.__name__[len('Thing_'):]
40
41     def sound(self, name, msg):
42         from plomrogue.mapping import DijkstraMap
43         from plomrogue.misc import quote
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
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 = ' +--+ ' + ' |  | ' + '======'
170
171
172
173 class Thing_HatRemixer(Thing):
174     symbol_hint = 'H'
175
176     def accept(self, hat):
177         import string
178         new_design = ''
179         legal_chars = string.ascii_letters + string.digits + string.punctuation + ' '
180         for i in range(18):
181             new_design += random.choice(list(legal_chars))
182         hat.design = new_design
183         self.sound('HAT REMIXER', 'remixing a hat …')
184         self.game.changed = True
185
186
187
188 import datetime
189 class Thing_MusicPlayer(Thing):
190     symbol_hint = 'R'
191     commandable = True
192     portable = True
193     repeat = True
194     next_song_start = datetime.datetime.now()
195     playlist_index = -1
196     playing = True
197
198     def __init__(self, *args, **kwargs):
199         super().__init__(*args, **kwargs)
200         self.next_song_start = datetime.datetime.now()
201         self.playlist = []
202
203     def proceed(self):
204         if (not self.playing) or len(self.playlist) == 0:
205             return
206         if datetime.datetime.now() > self.next_song_start:
207             self.playlist_index += 1
208             if self.playlist_index == len(self.playlist):
209                 self.playlist_index = 0
210                 if not self.repeat:
211                     self.playing = False
212                     return
213             song_data = self.playlist[self.playlist_index]
214             self.next_song_start = datetime.datetime.now() +\
215                 datetime.timedelta(seconds=song_data[1])
216             self.sound('MUSICPLAYER', song_data[0])
217             self.game.changed = True
218
219     def interpret(self, command):
220         msg_lines = []
221         if command == 'HELP':
222             msg_lines += ['available commands:']
223             msg_lines += ['HELP – show this help']
224             msg_lines += ['ON/OFF – toggle playback on/off']
225             msg_lines += ['REWIND – return to start of playlist']
226             msg_lines += ['LIST – list programmed songs, durations']
227             msg_lines += ['SKIP – to skip to next song']
228             msg_lines += ['REPEAT – toggle playlist repeat on/off']
229             msg_lines += ['ADD LENGTH SONG – add SONG to playlist, with LENGTH in format "minutes:seconds", i.e. something like "0:47" or "11:02"']
230             return msg_lines
231         elif command == 'LIST':
232             msg_lines += ['playlist:']
233             i = 0
234             for entry in self.playlist:
235                 minutes = entry[1] // 60
236                 seconds = entry[1] % 60
237                 if seconds < 10:
238                     seconds = '0%s' % seconds
239                 selector = 'next:' if i == self.playlist_index else '     '
240                 msg_lines += ['%s %s:%s – %s' % (selector, minutes, seconds, entry[0])]
241                 i += 1
242             return msg_lines
243         elif command == 'ON/OFF':
244             self.playing = False if self.playing else True
245             self.game.changed = True
246             if self.playing:
247                 return ['playing']
248             else:
249                 return ['paused']
250         elif command == 'REMOVE':
251             if len(self.playlist) == 0:
252                 return ['playlist already empty']
253             del self.playlist[max(0, self.playlist_index)]
254             self.playlist_index -= 1
255             if self.playlist_index < -1:
256                 self.playlist_index = -1
257             self.game.changed = True
258             return ['removed song']
259         elif command == 'REWIND':
260             self.playlist_index = -1
261             self.next_song_start = datetime.datetime.now()
262             self.game.changed = True
263             return ['back at start of playlist']
264         elif command == 'SKIP':
265             self.next_song_start = datetime.datetime.now()
266             self.game.changed = True
267             return ['skipped']
268         elif command == 'REPEAT':
269             self.repeat = False if self.repeat else True
270             self.game.changed = True
271             if self.repeat:
272                 return ['playlist repeat turned on']
273             else:
274                 return ['playlist repeat turned off']
275         elif command.startswith('ADD '):
276             tokens = command.split(' ', 2)
277             if len(tokens) != 3:
278                 return ['wrong syntax, see HELP']
279             length = tokens[1].split(':')
280             if len(length) != 2:
281                 return ['wrong syntax, see HELP']
282             try:
283                 minutes = int(length[0])
284                 seconds = int(length[1])
285             except ValueError:
286                 return ['wrong syntax, see HELP']
287             self.playlist += [(tokens[2], minutes * 60 + seconds)]
288             self.game.changed = True
289             return ['added']
290         else:
291             return ['cannot understand command']
292
293
294
295 class Thing_BottleDeposit(Thing):
296     bottle_counter = 0
297     symbol_hint = 'O'
298
299     def proceed(self):
300         if self.bottle_counter >= 3:
301             self.bottle_counter = 0
302             choice = random.choice(['MusicPlayer', 'Hat'])
303             self.game.add_thing(choice, self.position)
304             msg = 'here is a gift as a reward for ecological consciousness –'
305             if choice == 'MusicPlayer':
306                 msg += 'pick it up and then use "command thing" on it!'
307             elif choice == 'Hat':
308                 msg += 'pick it up and then use "(un-)wear" on it!'
309             self.sound('BOTTLE DEPOSITOR', msg)
310             self.game.changed = True
311
312     def accept(self):
313         self.bottle_counter += 1
314         self.sound('BOTTLE DEPOSITOR',
315                    'thanks for this empty bottle – deposit %s more for a gift!' %
316                    (3 - self.bottle_counter))
317
318
319
320
321 class ThingAnimate(Thing):
322     blocking = True
323     drunk = 0
324
325     def __init__(self, *args, **kwargs):
326         super().__init__(*args, **kwargs)
327         self.next_task = [None]
328         self.task = None
329         self.invalidate_map_view()
330
331     def invalidate_map_view(self):
332         self._fov = None
333         self._visible_terrain = None
334         self._visible_control = None
335
336     def set_next_task(self, task_name, args=()):
337         task_class = self.game.tasks[task_name]
338         self.next_task = [task_class(self, args)]
339
340     def get_next_task(self):
341         if self.next_task[0]:
342             task = self.next_task[0]
343             self.next_task = [None]
344             task.check()
345             return task
346
347     def proceed(self):
348         self.drunk -= 1
349         if self.drunk == 0:
350             for c_id in self.game.sessions:
351                 if self.game.sessions[c_id]['thing_id'] == self.id_:
352                     # TODO: refactor with self.send_msg
353                     self.game.io.send('DEFAULT_COLORS', c_id)
354                     self.game.io.send('CHAT "You sober up."', c_id)
355                     self.invalidate_map_view()
356                     break
357             self.game.changed = True
358         if self.task is None:
359             self.task = self.get_next_task()
360             return
361         try:
362             self.task.check()
363         except (PlayError, GameError) as e:
364             self.task = None
365             raise e
366         self.task.todo -= 1
367         if self.task.todo <= 0:
368             self.task.do()
369             self.game.changed = True
370             self.task = self.get_next_task()
371
372     def prepare_multiprocessible_fov_stencil(self):
373         fov_map_class = self.game.map_geometry.fov_map_class
374         fov_radius = 3 if self.drunk > 0 else 12
375         self._fov = fov_map_class(self.game.things, self.game.maps,
376                                   self.position, fov_radius, self.game.get_map)
377
378     def multiprocessible_fov_stencil(self):
379         self._fov.init_terrain()
380
381     @property
382     def fov_stencil(self):
383         if self._fov:
384             return self._fov
385         # due to the pre-multiprocessing in game.send_gamestate,
386         # the following should actually never be called
387         self.prepare_multiprocessible_fov_stencil()
388         self.multiprocessible_fov_stencil()
389         return self._fov
390
391     def fov_stencil_make(self):
392         self._fov.make()
393
394     def fov_test(self, big_yx, little_yx):
395         test_position = self.fov_stencil.target_yx(big_yx, little_yx)
396         if self.fov_stencil.inside(test_position):
397             if self.fov_stencil[test_position] == '.':
398                 return True
399         return False
400
401     def fov_stencil_map(self, map_type):
402         visible_terrain = ''
403         for yx in self.fov_stencil:
404             if self.fov_stencil[yx] == '.':
405                 big_yx, little_yx = self.fov_stencil.source_yxyx(yx)
406                 map_ = self.game.get_map(big_yx, map_type)
407                 visible_terrain += map_[little_yx]
408             else:
409                 visible_terrain += ' '
410         return visible_terrain
411
412     @property
413     def visible_terrain(self):
414         if self._visible_terrain:
415             return self._visible_terrain
416         self._visible_terrain = self.fov_stencil_map('normal')
417         return self._visible_terrain
418
419     @property
420     def visible_control(self):
421         if self._visible_control:
422             return self._visible_control
423         self._visible_control = self.fov_stencil_map('control')
424         return self._visible_control
425
426
427
428 class Thing_Player(ThingAnimate):
429     symbol_hint = '@'
430
431     def __init__(self, *args, **kwargs):
432         super().__init__(*args, **kwargs)
433         self.carrying = None
434
435     def send_msg(self, msg):
436         for c_id in self.game.sessions:
437             if self.game.sessions[c_id]['thing_id'] == self.id_:
438                 self.game.io.send(msg, c_id)
439                 break
440
441     def uncarry(self):
442         t = self.carrying
443         t.carried = False
444         self.carrying = None
445         return t