home · contact · privacy
Improve chat message meta data display.
[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
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
248
249
250 import datetime
251 class Thing_MusicPlayer(Thing):
252     symbol_hint = 'R'
253     commandable = True
254     portable = True
255     repeat = True
256     next_song_start = datetime.datetime.now()
257     playlist_index = -1
258     playing = True
259
260     def __init__(self, *args, **kwargs):
261         super().__init__(*args, **kwargs)
262         self.next_song_start = datetime.datetime.now()
263         self.playlist = []
264
265     def proceed(self):
266         if (not self.playing) or len(self.playlist) == 0:
267             return
268         if datetime.datetime.now() > self.next_song_start:
269             self.playlist_index += 1
270             if self.playlist_index == len(self.playlist):
271                 self.playlist_index = 0
272                 if not self.repeat:
273                     self.playing = False
274                     return
275             song_data = self.playlist[self.playlist_index]
276             self.next_song_start = datetime.datetime.now() +\
277                 datetime.timedelta(seconds=song_data[1])
278             self.sound('MUSICPLAYER', song_data[0])
279             self.game.changed = True
280
281     def interpret(self, command):
282         msg_lines = []
283         if command == 'HELP':
284             msg_lines += ['available commands:']
285             msg_lines += ['HELP – show this help']
286             msg_lines += ['ON/OFF – toggle playback on/off']
287             msg_lines += ['REWIND – return to start of playlist']
288             msg_lines += ['LIST – list programmed songs, durations']
289             msg_lines += ['SKIP – to skip to next song']
290             msg_lines += ['REPEAT – toggle playlist repeat on/off']
291             msg_lines += ['ADD LENGTH SONG – add SONG to playlist, with LENGTH in format "minutes:seconds", i.e. something like "0:47" or "11:02"']
292             return msg_lines
293         elif command == 'LIST':
294             msg_lines += ['playlist:']
295             i = 0
296             for entry in self.playlist:
297                 minutes = entry[1] // 60
298                 seconds = entry[1] % 60
299                 if seconds < 10:
300                     seconds = '0%s' % seconds
301                 selector = 'next:' if i == self.playlist_index else '     '
302                 msg_lines += ['%s %s:%s – %s' % (selector, minutes, seconds, entry[0])]
303                 i += 1
304             return msg_lines
305         elif command == 'ON/OFF':
306             self.playing = False if self.playing else True
307             self.game.changed = True
308             if self.playing:
309                 return ['playing']
310             else:
311                 return ['paused']
312         elif command == 'REMOVE':
313             if len(self.playlist) == 0:
314                 return ['playlist already empty']
315             del self.playlist[max(0, self.playlist_index)]
316             self.playlist_index -= 1
317             if self.playlist_index < -1:
318                 self.playlist_index = -1
319             self.game.changed = True
320             return ['removed song']
321         elif command == 'REWIND':
322             self.playlist_index = -1
323             self.next_song_start = datetime.datetime.now()
324             self.game.changed = True
325             return ['back at start of playlist']
326         elif command == 'SKIP':
327             self.next_song_start = datetime.datetime.now()
328             self.game.changed = True
329             return ['skipped']
330         elif command == 'REPEAT':
331             self.repeat = False if self.repeat else True
332             self.game.changed = True
333             if self.repeat:
334                 return ['playlist repeat turned on']
335             else:
336                 return ['playlist repeat turned off']
337         elif command.startswith('ADD '):
338             tokens = command.split(' ', 2)
339             if len(tokens) != 3:
340                 return ['wrong syntax, see HELP']
341             length = tokens[1].split(':')
342             if len(length) != 2:
343                 return ['wrong syntax, see HELP']
344             try:
345                 minutes = int(length[0])
346                 seconds = int(length[1])
347             except ValueError:
348                 return ['wrong syntax, see HELP']
349             self.playlist += [(tokens[2], minutes * 60 + seconds)]
350             self.game.changed = True
351             return ['added']
352         else:
353             return ['cannot understand command']
354
355
356
357 class Thing_BottleDeposit(Thing):
358     bottle_counter = 0
359     symbol_hint = 'O'
360
361     def proceed(self):
362         if self.bottle_counter >= 3:
363             self.bottle_counter = 0
364             choice = random.choice(['MusicPlayer', 'Hat'])
365             self.game.add_thing(choice, self.position)
366             msg = 'here is a gift as a reward for ecological consciousness –'
367             if choice == 'MusicPlayer':
368                 msg += 'pick it up and then use "command thing" on it!'
369             elif choice == 'Hat':
370                 msg += 'pick it up and then use "(un-)wear" on it!'
371             self.sound('BOTTLE DEPOSITOR', msg)
372             self.game.changed = True
373
374     def accept(self):
375         self.bottle_counter += 1
376         self.sound('BOTTLE DEPOSITOR',
377                    'thanks for this empty bottle – deposit %s more for a gift!' %
378                    (3 - self.bottle_counter))
379
380
381
382
383 class ThingAnimate(Thing):
384     blocking = True
385     drunk = 0
386
387     def __init__(self, *args, **kwargs):
388         super().__init__(*args, **kwargs)
389         self.next_task = [None]
390         self.task = None
391         self.invalidate_map_view()
392
393     def invalidate_map_view(self):
394         self._fov = None
395         self._visible_terrain = None
396         self._visible_control = None
397
398     def set_next_task(self, task_name, args=()):
399         task_class = self.game.tasks[task_name]
400         self.next_task = [task_class(self, args)]
401
402     def get_next_task(self):
403         if self.next_task[0]:
404             task = self.next_task[0]
405             self.next_task = [None]
406             task.check()
407             return task
408
409     def proceed(self):
410         self.drunk -= 1
411         if self.drunk == 0:
412             for c_id in self.game.sessions:
413                 if self.game.sessions[c_id]['thing_id'] == self.id_:
414                     # TODO: refactor with self.send_msg
415                     self.game.io.send('DEFAULT_COLORS', c_id)
416                     self.game.io.send('CHAT "You sober up."', c_id)
417                     self.invalidate_map_view()
418                     break
419             self.game.changed = True
420         if self.task is None:
421             self.task = self.get_next_task()
422             return
423         try:
424             self.task.check()
425         except (PlayError, GameError) as e:
426             self.task = None
427             raise e
428         self.task.todo -= 1
429         if self.task.todo <= 0:
430             self.task.do()
431             self.game.changed = True
432             self.task = self.get_next_task()
433
434     def prepare_multiprocessible_fov_stencil(self):
435         fov_map_class = self.game.map_geometry.fov_map_class
436         fov_radius = 3 if self.drunk > 0 else 12
437         self._fov = fov_map_class(self.game.things, self.game.maps,
438                                   self.position, fov_radius, self.game.get_map)
439
440     def multiprocessible_fov_stencil(self):
441         self._fov.init_terrain()
442
443     @property
444     def fov_stencil(self):
445         if self._fov:
446             return self._fov
447         # due to the pre-multiprocessing in game.send_gamestate,
448         # the following should actually never be called
449         self.prepare_multiprocessible_fov_stencil()
450         self.multiprocessible_fov_stencil()
451         return self._fov
452
453     def fov_stencil_make(self):
454         self._fov.make()
455
456     def fov_test(self, big_yx, little_yx):
457         test_position = self.fov_stencil.target_yx(big_yx, little_yx)
458         if self.fov_stencil.inside(test_position):
459             if self.fov_stencil[test_position] == '.':
460                 return True
461         return False
462
463     def fov_stencil_map(self, map_type):
464         visible_terrain = ''
465         for yx in self.fov_stencil:
466             if self.fov_stencil[yx] == '.':
467                 big_yx, little_yx = self.fov_stencil.source_yxyx(yx)
468                 map_ = self.game.get_map(big_yx, map_type)
469                 visible_terrain += map_[little_yx]
470             else:
471                 visible_terrain += ' '
472         return visible_terrain
473
474     @property
475     def visible_terrain(self):
476         if self._visible_terrain:
477             return self._visible_terrain
478         self._visible_terrain = self.fov_stencil_map('normal')
479         return self._visible_terrain
480
481     @property
482     def visible_control(self):
483         if self._visible_control:
484             return self._visible_control
485         self._visible_control = self.fov_stencil_map('control')
486         return self._visible_control
487
488
489
490 class Thing_Player(ThingAnimate):
491     symbol_hint = '@'
492
493     def __init__(self, *args, **kwargs):
494         super().__init__(*args, **kwargs)
495         self.carrying = None
496
497     def send_msg(self, msg):
498         for c_id in self.game.sessions:
499             if self.game.sessions[c_id]['thing_id'] == self.id_:
500                 self.game.io.send(msg, c_id)
501                 break
502
503     def uncarry(self):
504         t = self.carrying
505         t.carried = False
506         self.carrying = None
507         return t