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
14 self.map_geometry = MapGeometrySquare(YX(32, 32))
17 def get_thing(self, id_):
18 for thing in self.things:
23 def _register_object(self, obj, obj_type_desc, prefix):
24 if not obj.__name__.startswith(prefix):
25 raise GameError('illegal %s object name: %s' % (obj_type_desc, obj.__name__))
26 obj_name = obj.__name__[len(prefix):]
27 d = getattr(self, obj_type_desc + 's')
30 def register_command(self, command):
31 self._register_object(command, 'command', 'cmd_')
35 class SaveableMap(Map):
38 def __setitem__(self, *args, **kwargs):
39 super().__setitem__(*args, **kwargs)
42 def set_line(self, *args, **kwargs):
43 super().set_line(*args, **kwargs)
47 if yx.y < 0 or yx.x < 0 or \
48 yx.y >= self.geometry.size.y or yx.x >= self.geometry.size.x:
52 def draw_presets(self, big_yx, type_):
55 self.terrain = 'X' * self.size_i
57 self.draw_presets_grid(big_yx)
59 def draw_presets_grid(self, big_yx):
60 old_modified = self.modified
61 if type(self.geometry) == MapGeometrySquare:
62 self.set_line(0, 'X' * self.geometry.size.x)
63 self.set_line(1, 'X' * self.geometry.size.x)
64 self.set_line(2, 'X' * self.geometry.size.x)
65 self.set_line(3, 'X' * self.geometry.size.x)
66 self.set_line(4, 'X' * self.geometry.size.x)
67 for y in range(self.geometry.size.y):
73 elif type(self.geometry) == MapGeometryHex:
74 # TODO: for this to work we need a map side length divisible by 6.
76 def draw_grid(offset=YX(0, 0)):
77 dirs = ('DOWNRIGHT', 'RIGHT', 'UPRIGHT', 'RIGHT')
79 def draw_snake(start):
85 for direction in dirs:
88 for dir_progress in range(distance):
89 mover = getattr(self.geometry, 'move__' + direction)
91 if yx.x >= self.geometry.size.x:
97 alternate_hex = big_yx.y % 2
99 draw_snake(offset + YX(0, 0))
100 draw_snake(offset + YX((0 + alternate_hex) * distance,
101 -int(1.5 * distance)))
102 draw_snake(offset + YX((1 + alternate_hex) * distance,
104 draw_snake(offset + YX((2 + alternate_hex) * distance,
105 -int(1.5 * distance)))
107 distance = self.geometry.size.y // 3
117 self.modified = old_modified
122 class Game(GameBase):
124 def __init__(self, save_file, *args, **kwargs):
126 from plomrogue.misc import Terrain
127 super().__init__(*args, **kwargs)
129 self.changed_tiles = {'fov': [], 'other': []}
130 self.io = GameIO(self, save_file)
131 self.login_requests = []
133 self.thing_types = {}
138 self.map_controls = {}
139 self.map_control_passwords = {}
140 self.annotations = {}
141 self.spawn_points = []
143 self.intro_messages = []
144 self.player_chars = string.digits + string.ascii_letters
145 self.players_hat_chars = {}
146 self.player_char_i = -1
147 self.admin_passwords = []
148 self.send_gamestate_min_interval = datetime.timedelta(seconds=0.04)
149 self.last_send_gamestate = datetime.datetime.now() -\
150 self.send_gamestate_min_interval
152 '.': Terrain('.', 'floor'),
153 'X': Terrain('X', 'wall', blocks_light=True, blocks_sound=True,
154 blocks_movement=True),
155 '=': Terrain('=', 'glass', blocks_sound=True, blocks_movement=True),
156 'T': Terrain('T', 'table', blocks_movement=True),
158 self.draw_control_presets = 1
159 if os.path.exists(self.io.save_file):
160 if not os.path.isfile(self.io.save_file):
161 raise GameError('save file path refers to non-file')
162 self.io.train_parser()
164 def register_thing_type(self, thing_type):
165 self._register_object(thing_type, 'thing_type', 'Thing_')
166 self.io.train_parser()
168 def register_task(self, task):
169 self._register_object(task, 'task', 'Task_')
171 def read_savefile(self):
172 if os.path.exists(self.io.save_file):
173 with open(self.io.save_file, 'r') as f:
174 lines = f.readlines()
175 for i in range(len(lines)):
177 print("FILE INPUT LINE %5s: %s" % (i, line), end='')
178 self.io.handle_input(line, god_mode=True)
180 def can_do_thing_with_pw(self, thing, pw):
181 if thing.protection in self.map_control_passwords.keys():
182 if pw != self.map_control_passwords[thing.protection]:
186 def can_do_tile_with_pw(self, big_yx, little_yx, pw):
187 map_control = self.get_map(big_yx, 'control')
188 tile_class = map_control[little_yx]
189 if tile_class in self.map_control_passwords.keys():
190 tile_pw = self.map_control_passwords[tile_class]
195 def get_default_spawn_point(self):
197 if len(self.spawn_points) == 0:
198 return (YX(0, 0), YX(0, 0))
199 return random.choice(self.spawn_points)
201 def get_map_geometry_shape(self):
202 return self.map_geometry.__class__.__name__[len('MapGeometry'):]
204 def get_player(self, connection_id):
205 if connection_id not in self.sessions:
207 player = self.get_thing(self.sessions[connection_id]['thing_id'])
210 def get_face(self, t):
211 if t.type_ == 'Player':
212 if t.name in self.faces:
213 return self.faces[t.name]
215 return '/O O\\' + '| oo |' + '\\>--</'
218 def remove_thing(self, t):
221 self.things.remove(t)
222 self.record_change(t.position, 'other')
224 self.record_change(t.position, 'fov')
226 def add_thing(self, type_, position, id_=0):
229 t_old = self.get_thing(id_)
230 t = self.thing_types[type_](self, id_=id_, position=position)
232 self.things[self.things.index(t_old)] = t
235 self.record_change(t.position, 'other')
237 self.record_change(t.position, 'fov')
240 def send_gamestate(self, connection_id=None):
241 """Send out game state data relevant to clients."""
243 # TODO: limit to connection_id if provided
244 from plomrogue.mapping import FovMap
245 import multiprocessing
247 c_ids = [connection_id]
249 c_ids = [c_id for c_id in self.sessions]
250 # Only recalc FOVs for players with ._fov = None
252 player_ids_send_fov = []
253 player_ids_send_other = []
255 player = self.get_player(c_id)
257 player.prepare_multiprocessible_fov_stencil()
258 player_fovs += [player._fov]
259 player_ids_send_fov += [player.id_]
260 if None in (player._seen_things,
261 player._seen_annotation_positions,
262 player._seen_portal_positions):
263 player_ids_send_other += [player.id_]
265 single_core_until = 16 # since multiprocess has its own overhead
266 if len(player_fovs) > single_core_until:
267 pool = multiprocessing.Pool()
268 new_fovs = pool.map(FovMap.init_terrain, [fov for fov in player_fovs])
271 elif len(player_fovs) <= single_core_until:
272 for fov in player_fovs:
273 new_fovs += [fov.init_terrain()]
274 for i in range(len(player_ids_send_fov)):
275 id_ = player_ids_send_fov[i]
276 player = self.get_thing(id_)
277 player._fov = new_fovs[i]
279 self.io.send('TURN ' + str(self.turn), c_id)
280 player = self.get_player(c_id)
281 self.io.send('PLAYERS_HAT_CHARS ' + quote(player.get_cookie_chars()),
283 self.io.send('STATS %s %s' % (player.need_for_toilet,
284 player.energy), c_id)
285 if player.id_ in player_ids_send_fov:
286 self.io.send('FOV %s' % quote(player.fov_stencil.terrain), c_id)
287 self.io.send('MAP %s %s %s' % (self.get_map_geometry_shape(),
288 player.fov_stencil.geometry.size,
289 quote(player.visible_terrain)), c_id)
290 self.io.send('MAP_CONTROL %s' % quote(player.visible_control), c_id)
291 if player.id_ in player_ids_send_other:
292 self.io.send('OTHER_WIPE', c_id)
293 for t in player.seen_things:
294 target_yx = player.fov_stencil.target_yx(*t.position)
295 self.io.send('THING %s %s %s %s %s %s'
296 % (target_yx, t.type_, quote(t.protection), t.id_,
297 int(t.portable), int(t.commandable)),
299 if hasattr(t, 'name'):
300 self.io.send('THING_NAME %s %s' % (t.id_, quote(t.name)), c_id)
301 if t.type_ == 'Player' and t.name in self.hats:
302 hat = self.hats[t.name]
303 self.io.send('THING_HAT %s %s' % (t.id_, quote(hat)), c_id)
304 face = self.get_face(t)
306 self.io.send('THING_FACE %s %s' % (t.id_, quote(face)), c_id)
307 if hasattr(t, 'thing_char'):
308 self.io.send('THING_CHAR %s %s' % (t.id_,
309 quote(t.thing_char)), c_id)
310 if hasattr(t, 'installable') and not t.portable:
311 self.io.send('THING_INSTALLED %s' % (t.id_), c_id)
312 if hasattr(t, 'design'):
313 self.io.send('THING_DESIGN %s %s %s'
314 % (t.id_, t.design_size, quote(t.design)),
316 for t in [t for t in player.seen_things if t.carrying]:
317 # send this last so all carryable things are already created
318 self.io.send('THING_CARRYING %s %s' % (t.id_, t.carrying.id_),
320 for position in player.seen_portal_positions:
321 target_yx = player.fov_stencil.target_yx(position[0],
323 portal = self.portals[position[0]][position[1]]
324 self.io.send('PORTAL %s %s' % (target_yx, quote(portal)), c_id)
325 for position in player.seen_annotation_positions:
326 target_yx = player.fov_stencil.target_yx(position[0],
328 annotation = self.annotations[position[0]][position[1]]
329 self.io.send('ANNOTATION %s %s' % (target_yx,
330 quote(annotation)), c_id)
331 self.io.send('GAME_STATE_COMPLETE', c_id)
333 def record_change(self, position, type_):
334 big_yx, little_yx = position
335 self.changed_tiles[type_] += [self.map_geometry.undouble_yxyx(big_yx,
339 def login(self, nick, connection_id):
340 login_limit_filename = 'login_limit'
341 if os.path.exists(login_limit_filename):
342 with open(login_limit_filename, 'r') as f:
343 lines = f.readlines()
344 login_limit = int(lines[0])
345 if len(self.sessions) > login_limit - 1:
346 print('DEBUG LOGIN TOO MANY FOR', nick, connection_id)
347 self.io.send('CHAT "sorry, too many users currently '
348 'logged in, try again later '
349 'by re-entering your name"', connection_id)
351 for t in [t for t in self.things
352 if t.type_ == 'Player' and t.name == nick]:
353 self.io.send('GAME_ERROR ' + quote('name already in use'),
356 t = self.add_thing('Player', self.get_default_spawn_point())
358 t.thing_char = self.get_next_player_char()
359 self.sessions[connection_id] = {
363 print('DEBUG LOGIN', t.name, len(self.sessions))
364 self.io.send('PLAYER_ID %s' % t.id_, connection_id)
365 self.io.send('LOGIN_OK', connection_id)
366 for msg in self.intro_messages:
367 self.io.send('CHAT ' + quote(msg), connection_id)
368 self.io.send('CHAT ' + quote(t.name + ' entered the map.'))
369 for s in [s for s in self.things
370 if s.type_ == 'SpawnPoint' and s.name == t.name]:
371 t.position = s.position
379 # update player sessions
381 for connection_id in self.sessions:
382 connection_id_found = False
383 for server in self.io.servers:
384 if connection_id in server.clients:
385 connection_id_found = True
387 if not connection_id_found:
388 t = self.get_player(connection_id)
389 if hasattr(t, 'name'):
390 self.io.send('CHAT ' + quote(t.name + ' left the map.'))
391 spawn_point = self.add_thing('SpawnPoint', t.position)
392 spawn_point.temporary = True
393 spawn_point.name = t.name
394 print('DEBUG LEFT MAP', t.name)
396 to_delete += [connection_id]
397 for connection_id in to_delete:
398 del self.sessions[connection_id]
399 while len(self.login_requests) > 0:
400 login_request = self.login_requests.pop()
401 self.login(login_request[0], login_request[1])
404 for t in [t for t in self.things]:
408 except GameError as e:
409 for connection_id in [c_id for c_id in self.sessions
410 if self.sessions[c_id]['thing_id'] == t.id_]:
411 self.io.send('GAME_ERROR ' + quote(str(e)), connection_id)
412 except PlayError as e:
413 for connection_id in [c_id for c_id in self.sessions
414 if self.sessions[c_id]['thing_id'] == t.id_]:
415 self.io.send('PLAY_ERROR ' + quote(str(e)), connection_id)
417 # send gamestate if it makes sense at this point
420 # send_gamestate() can be rather expensive, due to among other reasons
421 # re-calculating players' FOVs, so don't send it out too often
422 if self.last_send_gamestate < \
423 datetime.datetime.now() - self.send_gamestate_min_interval:
425 for type_ in self.changed_tiles:
426 n_changes += len(self.changed_tiles[type_])
428 for t in [t for t in self.things if t.type_ == 'Player']:
429 fov_radius = 12 # TODO: un-hardcode
431 self.map_geometry.undouble_yxyx(t.position[0],
433 y_range_start = absolute_position.y - fov_radius
434 y_range_end = absolute_position.y + fov_radius
435 x_range_start = absolute_position.x - fov_radius
436 x_range_end = absolute_position.x + fov_radius
437 # TODO: refactor with SourcedMap.inside?
438 for type_ in self.changed_tiles:
439 for position in self.changed_tiles[type_]:
440 if position.y < y_range_start\
441 or position.y > y_range_end:
443 if position.x < x_range_start\
444 or position.x > x_range_end:
448 self.send_gamestate()
450 self.changed_tiles = {'fov': [], 'other': []}
452 self.last_send_gamestate = datetime.datetime.now()
454 def get_command(self, command_name):
456 def partial_with_attrs(f, *args, **kwargs):
457 from functools import partial
458 p = partial(f, *args, **kwargs)
459 p.__dict__.update(f.__dict__)
462 def cmd_TASK_colon(task_name, game, *args, connection_id):
463 t = self.get_player(connection_id)
465 raise GameError('Not registered as player.')
466 t.set_next_task(task_name, args)
468 def task_prefixed(command_name, task_prefix, task_command):
469 if command_name.startswith(task_prefix):
470 task_name = command_name[len(task_prefix):]
471 if task_name in self.tasks:
472 f = partial_with_attrs(task_command, task_name, self)
473 task = self.tasks[task_name]
474 f.argtypes = task.argtypes
478 command = task_prefixed(command_name, 'TASK:', cmd_TASK_colon)
481 if command_name in self.commands:
482 f = partial_with_attrs(self.commands[command_name], self)
486 def new_thing_id(self):
487 if len(self.things) == 0:
489 return max([t.id_ for t in self.things]) + 1
491 def get_next_player_char(self):
492 self.player_char_i += 1
493 if self.player_char_i >= len(self.player_chars):
494 self.player_char_i = 0
495 return self.player_chars[self.player_char_i]
497 def get_foo_blockers(self, foo):
499 for t in self.terrains.values():
500 block_attr = getattr(t, 'blocks_' + foo)
502 foo_blockers += t.character
505 def get_sound_blockers(self):
506 return self.get_foo_blockers('sound')
508 def get_light_blockers(self):
509 return self.get_foo_blockers('light')
511 def get_movement_blockers(self):
512 return self.get_foo_blockers('movement')
514 def get_flatland(self):
515 for t in self.terrains.values():
516 if not t.blocks_movement:
524 with open(self.io.save_file, 'w') as f:
525 write(f, 'TURN %s' % self.turn)
526 map_geometry_shape = self.get_map_geometry_shape()
527 # must come before MAP, otherwise first get_map uses the default
528 # TODO: refactor into MAP
529 write(f, 'MAP_CONTROL_PRESETS %s' % self.draw_control_presets)
530 write(f, 'MAP %s %s' % (map_geometry_shape, self.map_geometry.size,))
531 for terrain in self.terrains.values():
532 write(f, 'TERRAIN %s %s %s %s %s' % (quote(terrain.character),
533 quote(terrain.description),
534 int(terrain.blocks_light),
535 int(terrain.blocks_sound),
536 int(terrain.blocks_movement)))
537 if len(terrain.tags) > 0:
538 for tag in terrain.tags:
539 write(f, 'TERRAIN_TAG %s %s' % (quote(terrain.character),
541 for big_yx in [yx for yx in self.maps if self.maps[yx].modified]:
542 for y, line in self.maps[big_yx].lines():
543 write(f, 'MAP_LINE %s %5s %s' % (big_yx, y, quote(line)))
544 for big_yx in self.annotations:
545 for little_yx in self.annotations[big_yx]:
546 write(f, 'GOD_ANNOTATE %s %s %s' %
547 (big_yx, little_yx, quote(self.annotations[big_yx][little_yx])))
548 for big_yx in self.portals:
549 for little_yx in self.portals[big_yx]:
550 write(f, 'GOD_PORTAL %s %s %s' % (big_yx, little_yx,
551 quote(self.portals[big_yx][little_yx])))
552 for big_yx in [yx for yx in self.map_controls
553 if self.map_controls[yx].modified]:
554 for y, line in self.map_controls[big_yx].lines():
555 write(f, 'MAP_CONTROL_LINE %s %5s %s' % (big_yx, y, quote(line)))
556 for tile_class in self.map_control_passwords:
557 write(f, 'MAP_CONTROL_PW %s %s' % (tile_class,
558 self.map_control_passwords[tile_class]))
559 for pw in self.admin_passwords:
560 write(f, 'ADMIN_PASSWORD %s' % pw)
561 for name in self.faces:
562 write(f, 'GOD_PLAYER_FACE %s %s' % (quote(name),
563 quote(self.faces[name])))
564 for name in self.hats:
565 write(f, 'GOD_PLAYER_HAT %s %s' % (quote(name),
566 quote(self.hats[name])))
567 for name in self.players_hat_chars:
568 write(f, 'GOD_PLAYERS_HAT_CHARS %s %s' %
569 (quote(name), quote(self.players_hat_chars[name])))
570 for t in [t for t in self.things if not t.type_ == 'Player']:
571 write(f, 'THING %s %s %s %s' % (t.position[0],
572 t.position[1], t.type_, t.id_))
573 write(f, 'GOD_THING_PROTECTION %s %s' % (t.id_, quote(t.protection)))
574 if hasattr(t, 'name'):
575 write(f, 'GOD_THING_NAME %s %s' % (t.id_, quote(t.name)))
576 if hasattr(t, 'installable') and (not t.portable):
577 write(f, 'THING_INSTALLED %s' % t.id_)
578 if hasattr(t, 'design'):
580 write(f, 'GOD_THING_DESIGN_SIZE %s %s' % (t.id_,
582 write(f, 'GOD_THING_DESIGN %s %s' % (t.id_, quote(t.design)))
583 if t.type_ == 'Door' and t.blocks_movement:
584 write(f, 'THING_DOOR_CLOSED %s %s' % (t.id_, int(t.locked)))
585 elif t.type_ == 'MusicPlayer':
586 write(f, 'THING_MUSICPLAYER_SETTINGS %s %s %s %s' %
587 (t.id_, int(t.playing), t.playlist_index, int(t.repeat)))
588 for item in t.playlist:
589 write(f, 'THING_MUSICPLAYER_PLAYLIST_ITEM %s %s %s' %
590 (t.id_, quote(item[0]), item[1]))
591 elif t.type_ == 'Bottle' and not t.full:
592 write(f, 'THING_BOTTLE_EMPTY %s' % t.id_)
593 elif t.type_ == 'DoorKey':
594 write(f, 'THING_DOOR_KEY %s %s' % (t.id_, t.door.id_))
595 elif t.type_ == 'Crate':
596 for item in t.content:
597 write(f, 'THING_CRATE_ITEM %s %s' % (t.id_, item.id_))
598 elif t.type_ == 'SpawnPoint':
601 timestamp = int(t.created_at.timestamp())
602 write(f, 'THING_SPAWNPOINT_CREATED %s %s' % (t.id_,
604 next_thing_id = self.new_thing_id()
605 for t in [t for t in self.things if t.type_ == 'Player']:
606 write(f, 'THING %s %s SpawnPoint %s'
607 % (t.position[0], t.position[1], next_thing_id))
608 write(f, 'GOD_THING_NAME %s %s' % (next_thing_id, t.name))
609 write(f, 'THING_SPAWNPOINT_CREATED %s %s'
610 % (next_thing_id, int(datetime.datetime.now().timestamp())))
612 for s in self.spawn_points:
613 write(f, 'SPAWN_POINT %s %s' % (s[0], s[1]))
614 for msg in self.intro_messages:
615 write(f, 'INTRO_MSG %s' % quote(msg))
619 def get_map(self, big_yx, type_='normal'):
620 if type_ == 'normal':
622 elif type_ == 'control':
623 maps = self.map_controls
624 if big_yx not in maps:
625 maps[big_yx] = SaveableMap(self.map_geometry)
626 if type_ == 'control':
627 maps[big_yx].draw_presets(big_yx, self.draw_control_presets)
630 def new_world(self, map_geometry):
632 self.map_controls = {}
633 self.annotations = {}
635 self.admin_passwords = []
636 self.map_geometry = map_geometry
637 self.io.train_parser()
638 self.map_control_passwords = {'X': 'secret'}
639 self.get_map(YX(0, 0))
640 self.get_map(YX(0, 0), 'control')
641 self.annotations = {}