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