home · contact · privacy
Optimize send_gamestate, don't send any invisible state changes.
[plomrogue2] / plomrogue / game.py
1 from plomrogue.errors import GameError, PlayError
2 from plomrogue.io import GameIO
3 from plomrogue.misc import quote
4 from plomrogue.mapping import YX, MapGeometrySquare, MapGeometryHex, Map
5 import string
6 import datetime
7
8
9
10 class GameBase:
11
12     def __init__(self):
13         self.turn = 0
14         self.things = []
15         self.map_geometry = MapGeometrySquare(YX(24, 40))
16         self.commands = {}
17
18     def get_thing(self, id_):
19         for thing in self.things:
20             if id_ == thing.id_:
21                 return thing
22         return None
23
24     def _register_object(self, obj, obj_type_desc, prefix):
25         if not obj.__name__.startswith(prefix):
26             raise GameError('illegal %s object name: %s' % (obj_type_desc, obj.__name__))
27         obj_name = obj.__name__[len(prefix):]
28         d = getattr(self, obj_type_desc + 's')
29         d[obj_name] = obj
30
31     def register_command(self, command):
32         self._register_object(command, 'command', 'cmd_')
33
34
35
36 class SaveableMap(Map):
37     modified = False
38
39     def __setitem__(self, *args, **kwargs):
40         super().__setitem__(*args, **kwargs)
41         self.modified = True
42
43     def set_line(self, *args, **kwargs):
44         super().set_line(*args, **kwargs)
45         self.modified = True
46
47     def inside(self, yx):
48         if yx.y < 0 or yx.x < 0 or \
49            yx.y >= self.geometry.size.y or yx.x >= self.geometry.size.x:
50             return False
51         return True
52
53     def draw_presets(self, alternate_hex=0):
54         old_modified = self.modified
55         if type(self.geometry) == MapGeometrySquare:
56             self.set_line(0, 'X' * self.geometry.size.x)
57             self.set_line(1, 'X' * self.geometry.size.x)
58             self.set_line(2, 'X' * self.geometry.size.x)
59             self.set_line(3, 'X' * self.geometry.size.x)
60             self.set_line(4, 'X' * self.geometry.size.x)
61             for y in range(self.geometry.size.y):
62                 self[YX(y, 0)] = 'X'
63                 self[YX(y, 1)] = 'X'
64                 self[YX(y, 2)] = 'X'
65                 self[YX(y, 3)] = 'X'
66                 self[YX(y, 4)] = 'X'
67         elif type(self.geometry) == MapGeometryHex:
68             # TODO: for this to work we need a map side length divisible by 6.
69
70             def draw_grid(offset=YX(0, 0)):
71                 dirs = ('DOWNRIGHT', 'RIGHT', 'UPRIGHT', 'RIGHT')
72
73                 def draw_snake(start):
74                     keep_running = True
75                     yx = start
76                     if self.inside(yx):
77                         self[yx] = 'X'
78                     while keep_running:
79                         for direction in dirs:
80                             if not keep_running:
81                                 break
82                             for dir_progress in range(distance):
83                                 mover = getattr(self.geometry, 'move__' + direction)
84                                 yx = mover(yx)
85                                 if yx.x >= self.geometry.size.x:
86                                     keep_running = False
87                                     break
88                                 if self.inside(yx):
89                                     self[yx] = 'X'
90
91                 if alternate_hex:
92                     draw_snake(offset + YX(0, 0))
93                 draw_snake(offset + YX((0 + alternate_hex) * distance,
94                            -int(1.5 * distance)))
95                 draw_snake(offset + YX((1 + alternate_hex) * distance,
96                            0))
97                 draw_snake(offset + YX((2 + alternate_hex) * distance,
98                            -int(1.5 * distance)))
99
100             distance = self.geometry.size.y // 3
101             draw_grid()
102             draw_grid(YX(2, 0))
103             draw_grid(YX(0, 2))
104             draw_grid(YX(1, 0))
105             draw_grid(YX(0, 1))
106             draw_grid(YX(-1, 0))
107             draw_grid(YX(0, -1))
108             draw_grid(YX(-2, 0))
109             draw_grid(YX(0, -2))
110         self.modified = old_modified
111
112
113
114 import os
115 class Game(GameBase):
116
117     def __init__(self, save_file, *args, **kwargs):
118         super().__init__(*args, **kwargs)
119         self.changed = True
120         self.changed_tiles = []
121         self.io = GameIO(self, save_file)
122         self.tasks = {}
123         self.thing_types = {}
124         self.sessions = {}
125         self.faces = {}
126         self.hats = {}
127         self.maps = {}
128         self.map_controls = {}
129         self.map_control_passwords = {}
130         self.annotations = {}
131         self.spawn_point = YX(0, 0), YX(0, 0)
132         self.portals = {}
133         self.player_chars = string.digits + string.ascii_letters
134         self.player_char_i = -1
135         self.admin_passwords = []
136         self.send_gamestate_interval = datetime.timedelta(seconds=0.04)
137         self.last_send_gamestate = datetime.datetime.now() -\
138             self.send_gamestate_interval
139         self.terrains = {
140             '.': 'floor',
141             'X': 'wall',
142             '=': 'window',
143             '#': 'bed',
144             'T': 'desk',
145             '8': 'cupboard',
146             '[': 'glass door',
147             'o': 'sink',
148             'O': 'toilet'
149         }
150         if os.path.exists(self.io.save_file):
151             if not os.path.isfile(self.io.save_file):
152                 raise GameError('save file path refers to non-file')
153
154     def register_thing_type(self, thing_type):
155         self._register_object(thing_type, 'thing_type', 'Thing_')
156
157     def register_task(self, task):
158         self._register_object(task, 'task', 'Task_')
159
160     def read_savefile(self):
161         if os.path.exists(self.io.save_file):
162             with open(self.io.save_file, 'r') as f:
163                 lines = f.readlines()
164             for i in range(len(lines)):
165                 line = lines[i]
166                 print("FILE INPUT LINE %5s: %s" % (i, line), end='')
167                 self.io.handle_input(line, god_mode=True)
168
169     def can_do_thing_with_pw(self, thing, pw):
170         if thing.protection in self.map_control_passwords.keys():
171             if pw != self.map_control_passwords[thing.protection]:
172                 return False
173         return True
174
175     def can_do_tile_with_pw(self, big_yx, little_yx, pw):
176         map_control = self.get_map(big_yx, 'control')
177         tile_class = map_control[little_yx]
178         if tile_class in self.map_control_passwords.keys():
179             tile_pw = self.map_control_passwords[tile_class]
180             if pw != tile_pw:
181                 return False
182         return True
183
184     def get_string_options(self, string_option_type):
185         if string_option_type == 'direction':
186             return self.map_geometry.directions
187         elif string_option_type == 'direction+here':
188             return ['HERE'] + self.map_geometry.directions
189         elif string_option_type == 'char':
190             return [c for c in
191                     string.digits + string.ascii_letters + string.punctuation + ' ']
192         elif string_option_type == 'map_geometry':
193             return ['Hex', 'Square']
194         elif string_option_type == 'thing_type':
195             return self.thing_types.keys()
196         return None
197
198     def get_map_geometry_shape(self):
199         return self.map_geometry.__class__.__name__[len('MapGeometry'):]
200
201     def get_player(self, connection_id):
202         if connection_id not in self.sessions:
203             return None
204         player = self.get_thing(self.sessions[connection_id]['thing_id'])
205         return player
206
207     def get_face(self, t):
208         if t.type_ == 'Player':
209             if t.name in self.faces:
210                 return self.faces[t.name]
211             else:
212                 return '/O  O\\' + '| oo |' + '\\>--</'
213         return None
214
215     def remove_thing(self, t):
216         if t.carrying:
217             t.uncarry()
218         self.things.remove(t)
219         self.record_fov_change(t.position)
220
221     def add_thing(self, type_, position, id_=0):
222         t_old = None
223         if id_ > 0:
224             t_old = self.get_thing(id_)
225         t = self.thing_types[type_](self, id_=id_, position=position)
226         if t_old:
227             self.things[self.things.index(t_old)] = t
228         else:
229             self.things += [t]
230         self.record_fov_change(t.position)
231         return t
232
233     def send_gamestate(self, connection_id=None):
234         """Send out game state data relevant to clients."""
235
236         # TODO: limit to connection_id if provided
237         from plomrogue.mapping import FovMap
238         import multiprocessing
239         if connection_id:
240             c_ids = [connection_id]
241         else:
242             c_ids = [c_id for c_id in self.sessions]
243         # Only recalc FOVs for players with ._fov = None
244         player_fovs = []
245         player_fov_ids = []
246         for c_id in c_ids:
247             player = self.get_player(c_id)
248             if player._fov:
249                 continue
250             player.prepare_multiprocessible_fov_stencil()
251             player_fovs += [player._fov]
252             player_fov_ids += [player.id_]
253         new_fovs = []
254         single_core_until = 16  # since multiprocess has its own overhead
255         if len(player_fovs) > single_core_until:
256             pool = multiprocessing.Pool()
257             new_fovs = pool.map(FovMap.init_terrain, [fov for fov in player_fovs])
258             pool.close()
259             pool.join()
260         elif len(player_fovs) <= single_core_until:
261             for fov in player_fovs:
262                 new_fovs += [fov.init_terrain()]
263         for i in range(len(player_fov_ids)):
264             id_ = player_fov_ids[i]
265             player = self.get_thing(id_)
266             player._fov = new_fovs[i]
267         for c_id in c_ids:
268             self.io.send('TURN ' + str(self.turn), c_id)
269             player = self.get_player(c_id)
270             if player.id_ in player_fov_ids:
271                 self.io.send('FOV %s' % quote(player.fov_stencil.terrain), c_id)
272                 self.io.send('MAP %s %s %s' % (self.get_map_geometry_shape(),
273                                                player.fov_stencil.geometry.size,
274                                                quote(player.visible_terrain)), c_id)
275                 self.io.send('MAP_CONTROL %s' % quote(player.visible_control), c_id)
276             if player.id_ in player_fov_ids:
277                 # FIXME: Many of the following updates are triggered by technically
278                 # inappropriate calls to game.record_fov_change, since they depict
279                 # states that might change independent of FOV changes.  They are
280                 # collected here as a shortcut, but a cleaner way would be to
281                 # differentiate the changes somehow.
282                 self.io.send('PSEUDO_FOV_WIPE', c_id)
283                 for t in player.seen_things:
284                     target_yx = player.fov_stencil.target_yx(*t.position)
285                     self.io.send('THING %s %s %s %s %s %s'
286                                  % (target_yx, t.type_, quote(t.protection), t.id_,
287                                     int(t.portable), int(t.commandable)),
288                                  c_id)
289                     if hasattr(t, 'name'):
290                         self.io.send('THING_NAME %s %s' % (t.id_, quote(t.name)), c_id)
291                         if t.type_ == 'Player' and t.name in self.hats:
292                             hat = self.hats[t.name]
293                             self.io.send('THING_HAT %s %s' % (t.id_, quote(hat)), c_id)
294                     face = self.get_face(t)
295                     if face:
296                         self.io.send('THING_FACE %s %s' % (t.id_, quote(face)), c_id)
297                     if hasattr(t, 'thing_char'):
298                         self.io.send('THING_CHAR %s %s' % (t.id_,
299                                                            quote(t.thing_char)), c_id)
300                     if hasattr(t, 'installable') and not t.portable:
301                         self.io.send('THING_INSTALLED %s' % (t.id_), c_id)
302                     if hasattr(t, 'design'):
303                         self.io.send('THING_HAT %s %s' % (t.id_,
304                                                           quote(t.design)), c_id)
305                 for t in [t for t in player.seen_things if t.carrying]:
306                     # send this last so all carryable things are already created
307                     self.io.send('THING_CARRYING %s %s' % (t.id_, t.carrying.id_),
308                                  c_id)
309                 for big_yx in self.portals:
310                     for little_yx in [little_yx for little_yx in self.portals[big_yx]
311                                       if player.fov_test(big_yx, little_yx)]:
312                         target_yx = player.fov_stencil.target_yx(big_yx, little_yx)
313                         portal = self.portals[big_yx][little_yx]
314                         self.io.send('PORTAL %s %s' % (target_yx, quote(portal)), c_id)
315                 for big_yx in self.annotations:
316                     for little_yx in [little_yx for little_yx in self.annotations[big_yx]
317                                       if player.fov_test(big_yx, little_yx)]:
318                         target_yx = player.fov_stencil.target_yx(big_yx, little_yx)
319                         annotation = self.annotations[big_yx][little_yx]
320                         self.io.send('ANNOTATION %s %s' % (target_yx,
321                                                            quote(annotation)), c_id)
322             self.io.send('GAME_STATE_COMPLETE', c_id)
323
324     def record_fov_change(self, position):
325         big_yx, little_yx = position
326         self.changed_tiles += [self.map_geometry.undouble_yxyx(big_yx,
327                                                                little_yx)]
328         self.changed = True
329
330     def run_tick(self):
331         to_delete = []
332         for connection_id in self.sessions:
333             connection_id_found = False
334             for server in self.io.servers:
335                 if connection_id in server.clients:
336                     connection_id_found = True
337                     break
338             if not connection_id_found:
339                 t = self.get_player(connection_id)
340                 if hasattr(t, 'name'):
341                     self.io.send('CHAT ' + quote(t.name + ' left the map.'))
342                 self.remove_thing(t)
343                 to_delete += [connection_id]
344         for connection_id in to_delete:
345             del self.sessions[connection_id]
346             # self.changed = True  already handled by remove_thing
347         for t in [t for t in self.things]:
348             if t in self.things:
349                 try:
350                     t.proceed()
351                 except GameError as e:
352                     for connection_id in [c_id for c_id in self.sessions
353                                           if self.sessions[c_id]['thing_id'] == t.id_]:
354                         self.io.send('GAME_ERROR ' + quote(str(e)), connection_id)
355                 except PlayError as e:
356                     for connection_id in [c_id for c_id in self.sessions
357                                           if self.sessions[c_id]['thing_id'] == t.id_]:
358                         self.io.send('PLAY_ERROR ' + quote(str(e)), connection_id)
359         if self.changed:
360             self.turn += 1
361             # send_gamestate() can be rather expensive, due to among other reasons
362             # re-calculating players' FOVs, so don't send it out too often
363             if self.last_send_gamestate < \
364                datetime.datetime.now() -self.send_gamestate_interval:
365                 if len(self.changed_tiles) > 0:
366                     for t in [t for t in self.things if t.type_ == 'Player']:
367                         fov_radius = 12  # TODO: un-hardcode
368                         absolute_position =\
369                             self.map_geometry.undouble_yxyx(t.position[0],
370                                                             t.position[1])
371                         y_range_start = absolute_position.y - fov_radius
372                         y_range_end = absolute_position.y + fov_radius
373                         x_range_start = absolute_position.x - fov_radius
374                         x_range_end = absolute_position.x + fov_radius
375                         # TODO: refactor with SourcedMap.inside?
376                         for position in self.changed_tiles:
377                             if position.y < y_range_start\
378                                or position.y > y_range_end:
379                                 continue
380                             if position.x < x_range_start\
381                                or position.x > x_range_end:
382                                 continue
383                             t.invalidate_map_view()
384                             break
385                 self.send_gamestate()
386                 self.changed = False
387                 self.changed_tiles = []
388                 self.save()
389                 self.last_send_gamestate = datetime.datetime.now()
390
391     def get_command(self, command_name):
392
393         def partial_with_attrs(f, *args, **kwargs):
394             from functools import partial
395             p = partial(f, *args, **kwargs)
396             p.__dict__.update(f.__dict__)
397             return p
398
399         def cmd_TASK_colon(task_name, game, *args, connection_id):
400             t = self.get_player(connection_id)
401             if not t:
402                 raise GameError('Not registered as player.')
403             t.set_next_task(task_name, args)
404
405         def task_prefixed(command_name, task_prefix, task_command):
406             if command_name.startswith(task_prefix):
407                 task_name = command_name[len(task_prefix):]
408                 if task_name in self.tasks:
409                     f = partial_with_attrs(task_command, task_name, self)
410                     task = self.tasks[task_name]
411                     f.argtypes = task.argtypes
412                     return f
413             return None
414
415         command = task_prefixed(command_name, 'TASK:', cmd_TASK_colon)
416         if command:
417             return command
418         if command_name in self.commands:
419             f = partial_with_attrs(self.commands[command_name], self)
420             return f
421         return None
422
423     def new_thing_id(self):
424         if len(self.things) == 0:
425             return 1
426         return max([t.id_ for t in self.things]) + 1
427
428     def get_next_player_char(self):
429         self.player_char_i += 1
430         if self.player_char_i >= len(self.player_chars):
431             self.player_char_i = 0
432         return self.player_chars[self.player_char_i]
433
434     def save(self):
435
436         def write(f, msg):
437             f.write(msg + '\n')
438
439         with open(self.io.save_file, 'w') as f:
440             write(f, 'TURN %s' % self.turn)
441             map_geometry_shape = self.get_map_geometry_shape()
442             write(f, 'MAP %s %s' % (map_geometry_shape, self.map_geometry.size,))
443             for big_yx in [yx for yx in self.maps if self.maps[yx].modified]:
444                 for y, line in self.maps[big_yx].lines():
445                     write(f, 'MAP_LINE %s %5s %s' % (big_yx, y, quote(line)))
446             for big_yx in self.annotations:
447                 for little_yx in self.annotations[big_yx]:
448                     write(f, 'GOD_ANNOTATE %s %s %s' %
449                           (big_yx, little_yx, quote(self.annotations[big_yx][little_yx])))
450             for big_yx in self.portals:
451                 for little_yx in self.portals[big_yx]:
452                     write(f, 'GOD_PORTAL %s %s %s' % (big_yx, little_yx,
453                                                       quote(self.portals[big_yx][little_yx])))
454             for big_yx in [yx for yx in self.map_controls
455                            if self.map_controls[yx].modified]:
456                 for y, line in self.map_controls[big_yx].lines():
457                     write(f, 'MAP_CONTROL_LINE %s %5s %s' % (big_yx, y, quote(line)))
458             for tile_class in self.map_control_passwords:
459                 write(f, 'MAP_CONTROL_PW %s %s' % (tile_class,
460                                                    self.map_control_passwords[tile_class]))
461             for pw in self.admin_passwords:
462                 write(f, 'ADMIN_PASSWORD %s' % pw)
463             for name in self.faces:
464                 write(f, 'GOD_PLAYER_FACE %s %s' % (quote(name),
465                                                     quote(self.faces[name])))
466             for name in self.hats:
467                 write(f, 'GOD_PLAYER_HAT %s %s' % (quote(name),
468                                                    quote(self.hats[name])))
469             for t in [t for t in self.things if not t.type_ == 'Player']:
470                 write(f, 'THING %s %s %s %s' % (t.position[0],
471                                                 t.position[1], t.type_, t.id_))
472                 write(f, 'GOD_THING_PROTECTION %s %s' % (t.id_, quote(t.protection)))
473                 if hasattr(t, 'name'):
474                     write(f, 'GOD_THING_NAME %s %s' % (t.id_, quote(t.name)))
475                 if hasattr(t, 'installable') and (not t.portable):
476                     write(f, 'THING_INSTALLED %s' % t.id_)
477                 if t.type_ == 'Door' and t.blocking:
478                     write(f, 'THING_DOOR_CLOSED %s' % t.id_)
479                 elif t.type_ == 'Hat':
480                     write(f, 'THING_HAT_DESIGN %s %s' % (t.id_,
481                                                          quote(t.design)))
482                 elif t.type_ == 'MusicPlayer':
483                     write(f, 'THING_MUSICPLAYER_SETTINGS %s %s %s %s' %
484                           (t.id_, int(t.playing), t.playlist_index, int(t.repeat)))
485                     for item in t.playlist:
486                         write(f, 'THING_MUSICPLAYER_PLAYLIST_ITEM %s %s %s' %
487                               (t.id_, quote(item[0]), item[1]))
488                 elif t.type_ == 'Bottle' and not t.full:
489                     write(f, 'THING_BOTTLE_EMPTY %s' % t.id_)
490             write(f, 'SPAWN_POINT %s %s' % (self.spawn_point[0],
491                                             self.spawn_point[1]))
492
493     def get_map(self, big_yx, type_='normal'):
494         if type_ == 'normal':
495             maps = self.maps
496         elif type_ == 'control':
497             maps = self.map_controls
498         if big_yx not in maps:
499             maps[big_yx] = SaveableMap(self.map_geometry)
500             if type_ == 'control':
501                 maps[big_yx].draw_presets(big_yx.y % 2)
502         return maps[big_yx]
503
504     def new_world(self, map_geometry):
505         self.maps = {}
506         self.map_controls = {}
507         self.annotations = {}
508         self.portals = {}
509         self.admin_passwords = []
510         self.spawn_point = YX(0, 0), YX(0, 0)
511         self.map_geometry = map_geometry
512         self.map_control_passwords = {'X': 'secret'}
513         self.get_map(YX(0, 0))
514         self.get_map(YX(0, 0), 'control')
515         self.annotations = {}