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