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