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