home · contact · privacy
Refactor parser code.
[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 datetime
6
7
8
9 class GameBase:
10
11     def __init__(self):
12         self.turn = 0
13         self.things = []
14         self.map_geometry = MapGeometrySquare(YX(32, 32))
15         self.commands = {}
16
17     def get_thing(self, id_):
18         for thing in self.things:
19             if id_ == thing.id_:
20                 return thing
21         return None
22
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')
28         d[obj_name] = obj
29
30     def register_command(self, command):
31         self._register_object(command, 'command', 'cmd_')
32
33
34
35 class SaveableMap(Map):
36     modified = False
37
38     def __setitem__(self, *args, **kwargs):
39         super().__setitem__(*args, **kwargs)
40         self.modified = True
41
42     def set_line(self, *args, **kwargs):
43         super().set_line(*args, **kwargs)
44         self.modified = True
45
46     def inside(self, yx):
47         if yx.y < 0 or yx.x < 0 or \
48            yx.y >= self.geometry.size.y or yx.x >= self.geometry.size.x:
49             return False
50         return True
51
52     def draw_presets(self, big_yx, type_):
53         if type_ == 1:
54             if big_yx.y < 0:
55                 self.terrain = 'X' * self.size_i
56         elif type_ == 2:
57             self.draw_presets_grid(big_yx)
58
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):
68                 self[YX(y, 0)] = 'X'
69                 self[YX(y, 1)] = 'X'
70                 self[YX(y, 2)] = 'X'
71                 self[YX(y, 3)] = 'X'
72                 self[YX(y, 4)] = 'X'
73         elif type(self.geometry) == MapGeometryHex:
74             # TODO: for this to work we need a map side length divisible by 6.
75
76             def draw_grid(offset=YX(0, 0)):
77                 dirs = ('DOWNRIGHT', 'RIGHT', 'UPRIGHT', 'RIGHT')
78
79                 def draw_snake(start):
80                     keep_running = True
81                     yx = start
82                     if self.inside(yx):
83                         self[yx] = 'X'
84                     while keep_running:
85                         for direction in dirs:
86                             if not keep_running:
87                                 break
88                             for dir_progress in range(distance):
89                                 mover = getattr(self.geometry, 'move__' + direction)
90                                 yx = mover(yx)
91                                 if yx.x >= self.geometry.size.x:
92                                     keep_running = False
93                                     break
94                                 if self.inside(yx):
95                                     self[yx] = 'X'
96
97                 alternate_hex = big_yx.y % 2
98                 if alternate_hex:
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,
103                            0))
104                 draw_snake(offset + YX((2 + alternate_hex) * distance,
105                            -int(1.5 * distance)))
106
107             distance = self.geometry.size.y // 3
108             draw_grid()
109             draw_grid(YX(2, 0))
110             draw_grid(YX(0, 2))
111             draw_grid(YX(1, 0))
112             draw_grid(YX(0, 1))
113             draw_grid(YX(-1, 0))
114             draw_grid(YX(0, -1))
115             draw_grid(YX(-2, 0))
116             draw_grid(YX(0, -2))
117         self.modified = old_modified
118
119
120
121 import os
122 class Game(GameBase):
123
124     def __init__(self, save_file, *args, **kwargs):
125         import string
126         from plomrogue.misc import Terrain
127         super().__init__(*args, **kwargs)
128         self.changed = True
129         self.changed_tiles = {'fov': [], 'other': []}
130         self.io = GameIO(self, save_file)
131         self.login_requests = []
132         self.tasks = {}
133         self.thing_types = {}
134         self.sessions = {}
135         self.faces = {}
136         self.hats = {}
137         self.maps = {}
138         self.map_controls = {}
139         self.map_control_passwords = {}
140         self.annotations = {}
141         self.spawn_points = []
142         self.portals = {}
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
151         self.terrains = {
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),
157         }
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()
163
164     def register_thing_type(self, thing_type):
165         self._register_object(thing_type, 'thing_type', 'Thing_')
166         self.io.train_parser()
167
168     def register_task(self, task):
169         self._register_object(task, 'task', 'Task_')
170
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)):
176                 line = lines[i]
177                 print("FILE INPUT LINE %5s: %s" % (i, line), end='')
178                 self.io.handle_input(line, god_mode=True)
179
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]:
183                 return False
184         return True
185
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]
191             if pw != tile_pw:
192                 return False
193         return True
194
195     def get_default_spawn_point(self):
196         import random
197         if len(self.spawn_points) == 0:
198             return (YX(0, 0), YX(0, 0))
199         return random.choice(self.spawn_points)
200
201     def get_map_geometry_shape(self):
202         return self.map_geometry.__class__.__name__[len('MapGeometry'):]
203
204     def get_player(self, connection_id):
205         if connection_id not in self.sessions:
206             return None
207         player = self.get_thing(self.sessions[connection_id]['thing_id'])
208         return player
209
210     def get_face(self, t):
211         if t.type_ == 'Player':
212             if t.name in self.faces:
213                 return self.faces[t.name]
214             else:
215                 return '/O  O\\' + '| oo |' + '\\>--</'
216         return None
217
218     def remove_thing(self, t):
219         if t.carrying:
220             t.uncarry()
221         self.things.remove(t)
222         self.record_change(t.position, 'other')
223         if t.blocks_light:
224             self.record_change(t.position, 'fov')
225
226     def add_thing(self, type_, position, id_=0):
227         t_old = None
228         if id_ > 0:
229             t_old = self.get_thing(id_)
230         t = self.thing_types[type_](self, id_=id_, position=position)
231         if t_old:
232             self.things[self.things.index(t_old)] = t
233         else:
234             self.things += [t]
235         self.record_change(t.position, 'other')
236         if t.blocks_light:
237             self.record_change(t.position, 'fov')
238         return t
239
240     def send_gamestate(self, connection_id=None):
241         """Send out game state data relevant to clients."""
242
243         # TODO: limit to connection_id if provided
244         from plomrogue.mapping import FovMap
245         import multiprocessing
246         if connection_id:
247             c_ids = [connection_id]
248         else:
249             c_ids = [c_id for c_id in self.sessions]
250         # Only recalc FOVs for players with ._fov = None
251         player_fovs = []
252         player_ids_send_fov = []
253         player_ids_send_other = []
254         for c_id in c_ids:
255             player = self.get_player(c_id)
256             if not player._fov:
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_]
264         new_fovs = []
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])
269             pool.close()
270             pool.join()
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]
278         for c_id in c_ids:
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()),
282                          c_id)
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)),
298                                  c_id)
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)
305                     if face:
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)),
315                                      c_id)
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_),
319                                  c_id)
320                 for position in player.seen_portal_positions:
321                     target_yx = player.fov_stencil.target_yx(position[0],
322                                                              position[1])
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],
327                                                              position[1])
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)
332
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,
336                                                                       little_yx)]
337         self.changed = True
338
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)
350                     return
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'),
354                          connection_id)
355             return
356         t = self.add_thing('Player', self.get_default_spawn_point())
357         t.name = nick
358         t.thing_char = self.get_next_player_char()
359         self.sessions[connection_id] = {
360             'thing_id': t.id_,
361             'status': 'player'
362         }
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
372             if s.temporary:
373                 self.remove_thing(s)
374                 break
375         t.try_to_sit()
376
377     def run_tick(self):
378
379         # update player sessions
380         to_delete = []
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
386                     break
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)
395                 self.remove_thing(t)
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])
402
403         # update game state
404         for t in [t for t in self.things]:
405             if t in self.things:
406                 try:
407                     t.proceed()
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)
416
417         # send gamestate if it makes sense at this point
418         if self.changed:
419             self.turn += 1
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:
424                 n_changes = 0
425                 for type_ in self.changed_tiles:
426                     n_changes += len(self.changed_tiles[type_])
427                 if n_changes > 0:
428                     for t in [t for t in self.things if t.type_ == 'Player']:
429                         fov_radius = 12  # TODO: un-hardcode
430                         absolute_position =\
431                             self.map_geometry.undouble_yxyx(t.position[0],
432                                                             t.position[1])
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:
442                                     continue
443                                 if position.x < x_range_start\
444                                    or position.x > x_range_end:
445                                     continue
446                                 t.invalidate(type_)
447                                 break
448                 self.send_gamestate()
449                 self.changed = False
450                 self.changed_tiles = {'fov': [], 'other': []}
451                 self.save()
452                 self.last_send_gamestate = datetime.datetime.now()
453
454     def get_command(self, command_name):
455
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__)
460             return p
461
462         def cmd_TASK_colon(task_name, game, *args, connection_id):
463             t = self.get_player(connection_id)
464             if not t:
465                 raise GameError('Not registered as player.')
466             t.set_next_task(task_name, args)
467
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
475                     return f
476             return None
477
478         command = task_prefixed(command_name, 'TASK:', cmd_TASK_colon)
479         if command:
480             return command
481         if command_name in self.commands:
482             f = partial_with_attrs(self.commands[command_name], self)
483             return f
484         return None
485
486     def new_thing_id(self):
487         if len(self.things) == 0:
488             return 1
489         return max([t.id_ for t in self.things]) + 1
490
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]
496
497     def get_foo_blockers(self, foo):
498         foo_blockers = ''
499         for t in self.terrains.values():
500             block_attr = getattr(t, 'blocks_' + foo)
501             if block_attr:
502                 foo_blockers += t.character
503         return foo_blockers
504
505     def get_sound_blockers(self):
506         return self.get_foo_blockers('sound')
507
508     def get_light_blockers(self):
509         return self.get_foo_blockers('light')
510
511     def get_movement_blockers(self):
512         return self.get_foo_blockers('movement')
513
514     def get_flatland(self):
515         for t in self.terrains.values():
516             if not t.blocks_movement:
517                 return t.character
518
519     def save(self):
520
521         def write(f, msg):
522             f.write(msg + '\n')
523
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),
540                                                         quote(tag)))
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'):
579                     if t.type_ != 'Hat':
580                         write(f, 'GOD_THING_DESIGN_SIZE %s %s' % (t.id_,
581                                                                   t.design_size))
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':
599                     timestamp = 0
600                     if t.temporary:
601                         timestamp = int(t.created_at.timestamp())
602                     write(f, 'THING_SPAWNPOINT_CREATED %s %s' % (t.id_,
603                                                                  timestamp))
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())))
611                 next_thing_id += 1
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))
616
617
618
619     def get_map(self, big_yx, type_='normal'):
620         if type_ == 'normal':
621             maps = self.maps
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)
628         return maps[big_yx]
629
630     def new_world(self, map_geometry):
631         self.maps = {}
632         self.map_controls = {}
633         self.annotations = {}
634         self.portals = {}
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 = {}