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