home · contact · privacy
Turn Consumable into Bottle that may be full or empty.
[plomrogue2] / plomrogue / things.py
1 from plomrogue.errors import GameError
2 from plomrogue.mapping import YX
3
4
5
6 class ThingBase:
7     type_ = '?'
8
9     def __init__(self, game, id_=0, position=(YX(0, 0), YX(0, 0))):
10         self.game = game
11         if id_ == 0:
12             self.id_ = self.game.new_thing_id()
13         else:
14             self.id_ = id_
15         self.position = position
16
17
18
19 class Thing(ThingBase):
20     blocking = False
21     portable = False
22     protection = '.'
23     commandable = False
24
25     def __init__(self, *args, **kwargs):
26         super().__init__(*args, **kwargs)
27
28     def proceed(self):
29         pass
30
31     @property
32     def type_(self):
33         return self.__class__.get_type()
34
35     @classmethod
36     def get_type(cls):
37         return cls.__name__[len('Thing_'):]
38
39     def sound(self, name, msg):
40         from plomrogue.mapping import DijkstraMap
41         from plomrogue.misc import quote
42
43         def lower_msg_by_volume(msg, volume, largest_audible_distance):
44             import random
45             factor = largest_audible_distance / 4
46             lowered_msg = ''
47             for c in msg:
48                 c = c
49                 while random.random() > volume * factor:
50                     if c.isupper():
51                         c = c.lower()
52                     elif c != '.' and c != ' ':
53                         c = '.'
54                     else:
55                         c = ' '
56                 lowered_msg += c
57             return lowered_msg
58
59         largest_audible_distance = 20
60         # player's don't block sound (or should they?)
61         things = [t for t in self.game.things if t.type_ != 'Player']
62         dijkstra_map = DijkstraMap(things, self.game.maps, self.position,
63                                    largest_audible_distance, self.game.get_map)
64         for c_id in self.game.sessions:
65             listener = self.game.get_player(c_id)
66             target_yx = dijkstra_map.target_yx(*listener.position, True)
67             if not target_yx:
68                 continue
69             listener_distance = dijkstra_map[target_yx]
70             if listener_distance > largest_audible_distance:
71                 continue
72             volume = 1 / max(1, listener_distance)
73             lowered_msg = lower_msg_by_volume(msg, volume,
74                                               largest_audible_distance)
75             lowered_nick = lower_msg_by_volume(name, volume,
76                                                largest_audible_distance)
77             self.game.io.send('CHAT ' +
78                               quote('(volume: %.2f) %s: %s' % (volume,
79                                                                lowered_nick,
80                                                                lowered_msg)),
81                               c_id)
82
83
84
85 class Thing_Item(Thing):
86     symbol_hint = 'i'
87     portable = True
88
89
90
91 class ThingSpawner(Thing):
92     symbol_hint = 'S'
93
94     def proceed(self):
95         for t in [t for t in self.game.things
96                   if t != self and t.position == self.position]:
97             return
98         t = self.game.thing_types[self.child_type](self.game,
99                                                    position=self.position)
100         self.game.things += [t]
101         self.game.changed = True
102
103
104
105 class Thing_ItemSpawner(ThingSpawner):
106     child_type = 'Item'
107
108
109
110 class Thing_SpawnPointSpawner(ThingSpawner):
111     child_type = 'SpawnPoint'
112
113
114
115 class Thing_SpawnPoint(Thing):
116     symbol_hint = 's'
117     portable = True
118     name = 'username'
119
120
121
122 class Thing_DoorSpawner(ThingSpawner):
123     child_type = 'Door'
124
125
126
127 class Thing_Door(Thing):
128     symbol_hint = 'D'
129     blocking = False
130     portable = True
131
132     def open(self):
133         self.blocking = False
134         self.portable = True
135         del self.thing_char
136
137     def close(self):
138         self.blocking = True
139         self.portable = False
140         self.thing_char = '#'
141
142
143
144 class Thing_Bottle(Thing):
145     symbol_hint = 'B'
146     portable = True
147     full = True
148
149
150
151 class Thing_BottleSpawner(ThingSpawner):
152     child_type = 'Bottle'
153
154
155
156 import datetime
157 class Thing_MusicPlayer(Thing):
158     symbol_hint = 'R'
159     commandable = True
160     portable = True
161     playlist = []
162     repeat = True
163     next_song_start = datetime.datetime.now()
164     playlist_index = 0
165     playing = True
166
167     def __init__(self, *args, **kwargs):
168         super().__init__(*args, **kwargs)
169         self.next_song_start = datetime.datetime.now()
170
171     def proceed(self):
172         if (not self.playing) or len(self.playlist) == 0:
173             return
174         if datetime.datetime.now() > self.next_song_start:
175             song_data = self.playlist[self.playlist_index]
176             self.playlist_index += 1
177             if self.playlist_index == len(self.playlist):
178                 self.playlist_index = 0
179                 if not self.repeat:
180                     self.playing = False
181             self.next_song_start = datetime.datetime.now() +\
182                 datetime.timedelta(seconds=song_data[1])
183             self.sound('MUSICPLAYER', song_data[0])
184             self.game.changed = True
185
186     def interpret(self, command):
187         if command == 'HELP':
188             msg = 'available commands:\n'
189             msg += 'HELP – show this help\n'
190             msg += 'PLAY – toggle playback on/off\n'
191             msg += 'REWIND – return to start of playlist\n'
192             msg += 'LIST – list programmed songs, durations\n'
193             msg += 'SKIP – to skip to next song\n'
194             msg += 'REPEAT – toggle playlist repeat on/off\n'
195             msg += 'ADD LENGTH SONG – add SONG to playlist, with LENGTH in format "minutes:seconds", i.e. something like "0:47" or "11:02"'
196             return msg
197         elif command == 'LIST':
198             msg = 'playlist:'
199             i = 0
200             for entry in self.playlist:
201                 msg += '\n'
202                 minutes = entry[1] // 60
203                 seconds = entry[1] % 60
204                 if seconds < 10:
205                     seconds = '0%s' % seconds
206                 selector = 'next:' if i == self.playlist_index else '     '
207                 msg += '%s %s:%s – %s' % (selector, minutes, seconds, entry[0])
208                 i += 1
209             return msg
210         elif command == 'PLAY':
211             self.playing = False if self.playing else True
212             self.game.changed = True
213             if self.playing:
214                 return 'playing'
215             else:
216                 return 'paused'
217         elif command == 'REWIND':
218             self.playlist_index = 0
219             self.next_song_start = datetime.datetime.now()
220             self.game.changed = True
221             return 'back at start of playlist'
222         elif command == 'SKIP':
223             self.next_song_start = datetime.datetime.now()
224             self.game.changed = True
225             return 'skipped'
226         elif command == 'REPEAT':
227             self.repeat = False if self.repeat else True
228             self.game.changed = True
229             if self.repeat:
230                 return 'playlist repeat turned on'
231             else:
232                 return 'playlist repeat turned off'
233         elif command.startswith('ADD '):
234             tokens = command.split(' ', 2)
235             if len(tokens) != 3:
236                 return 'wrong syntax, see HELP'
237             length = tokens[1].split(':')
238             if len(length) != 2:
239                 return 'wrong syntax, see HELP'
240             try:
241                 minutes = int(length[0])
242                 seconds = int(length[1])
243             except ValueError:
244                 return 'wrong syntax, see HELP'
245             self.playlist += [(tokens[2], minutes * 60 + seconds)]
246             self.game.changed = True
247             return 'added'
248         else:
249             return 'cannot understand command'
250
251
252
253 class ThingAnimate(Thing):
254     blocking = True
255     drunk = 0
256
257     def __init__(self, *args, **kwargs):
258         super().__init__(*args, **kwargs)
259         self.next_tasks = []
260         self.set_task('WAIT')
261         self._fov = None
262
263     def set_task(self, task_name, args=()):
264         task_class = self.game.tasks[task_name]
265         self.task = task_class(self, args)
266         self.task.check()  # will throw GameError if necessary
267
268     def set_next_task(self, task_name, args=()):
269         task_class = self.game.tasks[task_name]
270         self.next_tasks += [task_class(self, args)]
271
272     def get_next_task(self):
273         if len(self.next_tasks) > 0:
274             task = self.next_tasks.pop(0)
275             task.check()
276             return task
277         else:
278             return None
279
280     def proceed(self):
281         self.drunk -= 1
282         if self.drunk == 0:
283             for c_id in self.game.sessions:
284                 if self.game.sessions[c_id]['thing_id'] == self.id_:
285                     self.game.io.send('DEFAULT_COLORS', c_id)
286                     self.game.io.send('CHAT "You sober up."', c_id)
287             self.game.changed = True
288         self._fov = None
289         if self.task is None:
290             self.task = self.get_next_task()
291             return
292         try:
293             self.task.check()
294         except GameError as e:
295             self.task = None
296             raise e
297         self.task.todo -= 1
298         if self.task.todo <= 0:
299             self._last_task_result = self.task.do()
300             self.game.changed = True
301             self.task = self.get_next_task()
302
303     @property
304     def fov_stencil(self):
305         if self._fov:
306             return self._fov
307         fov_map_class = self.game.map_geometry.fov_map_class
308         self._fov = fov_map_class(self.game.things, self.game.maps, self.position,
309                                   12, self.game.get_map)
310         return self._fov
311
312     def fov_test(self, big_yx, little_yx):
313         test_position = self.fov_stencil.target_yx(big_yx, little_yx)
314         if self.fov_stencil.inside(test_position):
315             if self.fov_stencil[test_position] == '.':
316                 return True
317         return False
318
319     def fov_stencil_map(self, map_type='normal'):
320         visible_terrain = ''
321         for yx in self.fov_stencil:
322             if self.fov_stencil[yx] == '.':
323                 big_yx, little_yx = self.fov_stencil.source_yxyx(yx)
324                 map_ = self.game.get_map(big_yx, map_type)
325                 visible_terrain += map_[little_yx]
326             else:
327                 visible_terrain += ' '
328         return visible_terrain
329
330
331
332 class Thing_Player(ThingAnimate):
333     symbol_hint = '@'
334
335     def __init__(self, *args, **kwargs):
336         super().__init__(*args, **kwargs)
337         self.carrying = None