home · contact · privacy
Fix square grid scrolling bug.
[plomrogue2] / plomrogue / game.py
1 from plomrogue.tasks import (Task_WAIT, Task_MOVE, Task_WRITE,
2                              Task_FLATTEN_SURROUNDINGS)
3 from plomrogue.errors import GameError, PlayError
4 from plomrogue.io import GameIO
5 from plomrogue.misc import quote
6 from plomrogue.mapping import YX, MapGeometrySquare, Map
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 import os
37 class Game(GameBase):
38
39     def __init__(self, save_file, *args, **kwargs):
40         super().__init__(*args, **kwargs)
41         self.changed = True
42         self.io = GameIO(self, save_file)
43         self.tasks = {}
44         self.thing_types = {}
45         self.sessions = {}
46         self.map = Map(self.map_geometry.size)
47         self.map_control = Map(self.map_geometry.size)
48         self.map_control_passwords = {}
49         self.annotations = {}
50         self.portals = {}
51         if os.path.exists(self.io.save_file):
52             if not os.path.isfile(self.io.save_file):
53                 raise GameError('save file path refers to non-file')
54
55     def register_thing_type(self, thing_type):
56         self._register_object(thing_type, 'thing_type', 'Thing_')
57
58     def register_task(self, task):
59         self._register_object(task, 'task', 'Task_')
60
61     def read_savefile(self):
62         if os.path.exists(self.io.save_file):
63             with open(self.io.save_file, 'r') as f:
64                 lines = f.readlines()
65             for i in range(len(lines)):
66                 line = lines[i]
67                 print("FILE INPUT LINE %5s: %s" % (i, line), end='')
68                 self.io.handle_input(line, god_mode=True)
69
70     def can_do_tile_with_pw(self, yx, pw):
71         tile_class = self.map_control[yx]
72         if tile_class in self.map_control_passwords:
73             tile_pw = self.map_control_passwords[tile_class]
74             if pw != tile_pw:
75                 return False
76         return True
77
78     def get_string_options(self, string_option_type):
79         import string
80         if string_option_type == 'direction':
81             return self.map_geometry.get_directions()
82         elif string_option_type == 'char':
83             return [c for c in
84                     string.digits + string.ascii_letters + string.punctuation + ' ']
85         elif string_option_type == 'map_geometry':
86             return ['Hex', 'Square']
87         elif string_option_type == 'thing_type':
88             return self.thing_types.keys()
89         return None
90
91     def get_map_geometry_shape(self):
92         return self.map_geometry.__class__.__name__[len('MapGeometry'):]
93
94     def send_gamestate(self, connection_id=None):
95         """Send out game state data relevant to clients."""
96
97         self.io.send('TURN ' + str(self.turn))
98         for c_id in self.sessions:
99             player = self.get_thing(self.sessions[c_id])
100             visible_terrain = player.fov_stencil_map(self.map)
101             self.io.send('FOV %s' % quote(player.fov_stencil.terrain), c_id)
102             self.io.send('MAP %s %s %s' % (self.get_map_geometry_shape(),
103                                            self.map_geometry.size,
104                                            quote(visible_terrain)), c_id)
105             visible_control = player.fov_stencil_map(self.map_control)
106             self.io.send('MAP_CONTROL %s' % quote(visible_control), c_id)
107             for t in [t for t in self.things
108                       if player.fov_stencil[t.position] == '.']:
109                 self.io.send('THING %s %s %s' % (t.position, t.type_, t.id_), c_id)
110                 if hasattr(t, 'nickname'):
111                     self.io.send('THING_NAME %s %s' % (t.id_,
112                                                        quote(t.nickname)), c_id)
113             for yx in [yx for yx in self.portals
114                        if player.fov_stencil[yx] == '.']:
115                 self.io.send('PORTAL %s %s' % (yx, quote(self.portals[yx])), c_id)
116         self.io.send('GAME_STATE_COMPLETE')
117
118     def run_tick(self):
119         to_delete = []
120         for connection_id in self.sessions:
121             connection_id_found = False
122             for server in self.io.servers:
123                 if connection_id in server.clients:
124                     connection_id_found = True
125                     break
126             if not connection_id_found:
127                 t = self.get_thing(self.sessions[connection_id])
128                 if hasattr(t, 'nickname'):
129                     self.io.send('CHAT ' + quote(t.nickname + ' left the map.'))
130                 self.things.remove(t)
131                 to_delete += [connection_id]
132         for connection_id in to_delete:
133             del self.sessions[connection_id]
134             self.changed = True
135         for t in [t for t in self.things]:
136             if t in self.things:
137                 try:
138                     t.proceed()
139                 except GameError as e:
140                     for connection_id in [c_id for c_id in self.sessions
141                                           if self.sessions[c_id] == t.id_]:
142                         self.io.send('GAME_ERROR ' + quote(str(e)), connection_id)
143                 except PlayError as e:
144                     for connection_id in [c_id for c_id in self.sessions
145                                           if self.sessions[c_id] == t.id_]:
146                         self.io.send('PLAY_ERROR ' + quote(str(e)), connection_id)
147         if self.changed:
148             self.turn += 1
149             self.send_gamestate()
150             self.changed = False
151             self.save()
152
153     def get_command(self, command_name):
154
155         def partial_with_attrs(f, *args, **kwargs):
156             from functools import partial
157             p = partial(f, *args, **kwargs)
158             p.__dict__.update(f.__dict__)
159             return p
160
161         def cmd_TASK_colon(task_name, game, *args, connection_id):
162             if connection_id not in game.sessions:
163                 raise GameError('Not registered as player.')
164             t = game.get_thing(game.sessions[connection_id])
165             t.set_next_task(task_name, args)
166
167         def task_prefixed(command_name, task_prefix, task_command):
168             if command_name.startswith(task_prefix):
169                 task_name = command_name[len(task_prefix):]
170                 if task_name in self.tasks:
171                     f = partial_with_attrs(task_command, task_name, self)
172                     task = self.tasks[task_name]
173                     f.argtypes = task.argtypes
174                     return f
175             return None
176
177         command = task_prefixed(command_name, 'TASK:', cmd_TASK_colon)
178         if command:
179             return command
180         if command_name in self.commands:
181             f = partial_with_attrs(self.commands[command_name], self)
182             return f
183         return None
184
185     def new_thing_id(self):
186         if len(self.things) == 0:
187             return 1
188         return max([t.id_ for t in self.things]) + 1
189
190     def save(self):
191
192       def write(f, msg):
193           f.write(msg + '\n')
194
195       with open(self.io.save_file, 'w') as f:
196           # TODO: save tasks
197           write(f, 'TURN %s' % self.turn)
198           map_geometry_shape = self.get_map_geometry_shape()
199           write(f, 'MAP %s %s' % (map_geometry_shape, self.map_geometry.size,))
200           for y, line in self.map.lines():
201               write(f, 'MAP_LINE %5s %s' % (y, quote(line)))
202           for yx in self.annotations:
203               write(f, 'GOD_ANNOTATE %s %s' % (yx, quote(self.annotations[yx])))
204           for yx in self.portals:
205               write(f, 'GOD_PORTAL %s %s' % (yx, quote(self.portals[yx])))
206           for y, line in self.map_control.lines():
207               write(f, 'MAP_CONTROL_LINE %5s %s' % (y, quote(line)))
208           for tile_class in self.map_control_passwords:
209               write(f, 'MAP_CONTROL_PW %s %s' % (tile_class,
210                                                  self.map_control_passwords[tile_class]))
211           for t in [t for t in self.things if not t.type_ == 'Player']:
212               write(f, 'THING %s %s %s' % (t.position, t.type_, t.id_))
213
214     def new_world(self, map_geometry):
215         self.map_geometry = map_geometry
216         self.map = Map(self.map_geometry.size)
217         self.map_control = Map(self.map_geometry.size)
218         self.annotations = {}