home · contact · privacy
38a607e69c01279b9e4e81be247e91d0dd28b71a
[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 import string
8
9
10
11 class GameBase:
12
13     def __init__(self):
14         self.turn = 0
15         self.things = []
16         self.map_geometry = MapGeometrySquare(YX(24, 40))
17         self.commands = {}
18
19     def get_thing(self, id_):
20         for thing in self.things:
21             if id_ == thing.id_:
22                 return thing
23         return None
24
25     def _register_object(self, obj, obj_type_desc, prefix):
26         if not obj.__name__.startswith(prefix):
27             raise GameError('illegal %s object name: %s' % (obj_type_desc, obj.__name__))
28         obj_name = obj.__name__[len(prefix):]
29         d = getattr(self, obj_type_desc + 's')
30         d[obj_name] = obj
31
32     def register_command(self, command):
33         self._register_object(command, 'command', 'cmd_')
34
35
36
37 import os
38 class Game(GameBase):
39
40     def __init__(self, save_file, *args, **kwargs):
41         super().__init__(*args, **kwargs)
42         self.changed = True
43         self.io = GameIO(self, save_file)
44         self.tasks = {}
45         self.thing_types = {}
46         self.sessions = {}
47         self.map = Map(self.map_geometry.size)
48         self.map_control = Map(self.map_geometry.size)
49         self.map_control_passwords = {}
50         self.annotations = {}
51         self.portals = {}
52         self.player_chars = string.digits + string.ascii_letters
53         self.player_char_i = -1
54         self.terrains = {
55             '.': 'floor',
56             'X': 'wall',
57             '=': 'window',
58             '#': 'bed',
59             'T': 'desk',
60             '8': 'cupboard',
61             '[': 'glass door',
62             'o': 'sink',
63             'O': 'toilet'
64         }
65         if os.path.exists(self.io.save_file):
66             if not os.path.isfile(self.io.save_file):
67                 raise GameError('save file path refers to non-file')
68
69     def register_thing_type(self, thing_type):
70         self._register_object(thing_type, 'thing_type', 'Thing_')
71
72     def register_task(self, task):
73         self._register_object(task, 'task', 'Task_')
74
75     def read_savefile(self):
76         if os.path.exists(self.io.save_file):
77             with open(self.io.save_file, 'r') as f:
78                 lines = f.readlines()
79             for i in range(len(lines)):
80                 line = lines[i]
81                 print("FILE INPUT LINE %5s: %s" % (i, line), end='')
82                 self.io.handle_input(line, god_mode=True)
83
84     def can_do_tile_with_pw(self, yx, pw):
85         tile_class = self.map_control[yx]
86         if tile_class in self.map_control_passwords:
87             tile_pw = self.map_control_passwords[tile_class]
88             if pw != tile_pw:
89                 return False
90         return True
91
92     def get_string_options(self, string_option_type):
93         if string_option_type == 'direction':
94             return self.map_geometry.get_directions()
95         elif string_option_type == 'char':
96             return [c for c in
97                     string.digits + string.ascii_letters + string.punctuation + ' ']
98         elif string_option_type == 'map_geometry':
99             return ['Hex', 'Square']
100         elif string_option_type == 'thing_type':
101             return self.thing_types.keys()
102         return None
103
104     def get_map_geometry_shape(self):
105         return self.map_geometry.__class__.__name__[len('MapGeometry'):]
106
107     def send_gamestate(self, connection_id=None):
108         """Send out game state data relevant to clients."""
109
110         self.io.send('TURN ' + str(self.turn))
111         for c_id in self.sessions:
112             player = self.get_thing(self.sessions[c_id])
113             visible_terrain = player.fov_stencil_map(self.map)
114             self.io.send('FOV %s' % quote(player.fov_stencil.terrain), c_id)
115             self.io.send('MAP %s %s %s' % (self.get_map_geometry_shape(),
116                                            player.fov_stencil.size,
117                                            quote(visible_terrain)), c_id)
118             visible_control = player.fov_stencil_map(self.map_control)
119             self.io.send('MAP_CONTROL %s' % quote(visible_control), c_id)
120             for t in [t for t in self.things if player.fov_test(t.position)]:
121                 corrected_yx = t.position - player.fov_stencil.offset
122                 self.io.send('THING %s %s %s' % (corrected_yx, t.type_, t.id_),
123                              c_id)
124                 if hasattr(t, 'name'):
125                     self.io.send('THING_NAME %s %s' % (t.id_, quote(t.name)), c_id)
126                 if hasattr(t, 'player_char'):
127                     self.io.send('THING_CHAR %s %s' % (t.id_,
128                                                        quote(t.player_char)), c_id)
129             for yx in [yx for yx in self.portals if player.fov_test(yx)]:
130                 corrected_yx = yx - player.fov_stencil.offset
131                 self.io.send('PORTAL %s %s' % (corrected_yx,
132                                                quote(self.portals[yx])), c_id)
133         self.io.send('GAME_STATE_COMPLETE')
134
135     def run_tick(self):
136         to_delete = []
137         for connection_id in self.sessions:
138             connection_id_found = False
139             for server in self.io.servers:
140                 if connection_id in server.clients:
141                     connection_id_found = True
142                     break
143             if not connection_id_found:
144                 t = self.get_thing(self.sessions[connection_id])
145                 if hasattr(t, 'name'):
146                     self.io.send('CHAT ' + quote(t.name + ' left the map.'))
147                 self.things.remove(t)
148                 to_delete += [connection_id]
149         for connection_id in to_delete:
150             del self.sessions[connection_id]
151             self.changed = True
152         for t in [t for t in self.things]:
153             if t in self.things:
154                 try:
155                     t.proceed()
156                 except GameError as e:
157                     for connection_id in [c_id for c_id in self.sessions
158                                           if self.sessions[c_id] == t.id_]:
159                         self.io.send('GAME_ERROR ' + quote(str(e)), connection_id)
160                 except PlayError as e:
161                     for connection_id in [c_id for c_id in self.sessions
162                                           if self.sessions[c_id] == t.id_]:
163                         self.io.send('PLAY_ERROR ' + quote(str(e)), connection_id)
164         if self.changed:
165             self.turn += 1
166             self.send_gamestate()
167             self.changed = False
168             self.save()
169
170     def get_command(self, command_name):
171
172         def partial_with_attrs(f, *args, **kwargs):
173             from functools import partial
174             p = partial(f, *args, **kwargs)
175             p.__dict__.update(f.__dict__)
176             return p
177
178         def cmd_TASK_colon(task_name, game, *args, connection_id):
179             if connection_id not in game.sessions:
180                 raise GameError('Not registered as player.')
181             t = game.get_thing(game.sessions[connection_id])
182             t.set_next_task(task_name, args)
183
184         def task_prefixed(command_name, task_prefix, task_command):
185             if command_name.startswith(task_prefix):
186                 task_name = command_name[len(task_prefix):]
187                 if task_name in self.tasks:
188                     f = partial_with_attrs(task_command, task_name, self)
189                     task = self.tasks[task_name]
190                     f.argtypes = task.argtypes
191                     return f
192             return None
193
194         command = task_prefixed(command_name, 'TASK:', cmd_TASK_colon)
195         if command:
196             return command
197         if command_name in self.commands:
198             f = partial_with_attrs(self.commands[command_name], self)
199             return f
200         return None
201
202     def new_thing_id(self):
203         if len(self.things) == 0:
204             return 1
205         return max([t.id_ for t in self.things]) + 1
206
207     def get_next_player_char(self):
208         self.player_char_i += 1
209         if self.player_char_i >= len(self.player_chars):
210             self.player_char_i = 0
211         return self.player_chars[self.player_char_i]
212
213     def save(self):
214
215       def write(f, msg):
216           f.write(msg + '\n')
217
218       with open(self.io.save_file, 'w') as f:
219           # TODO: save tasks
220           write(f, 'TURN %s' % self.turn)
221           map_geometry_shape = self.get_map_geometry_shape()
222           write(f, 'MAP %s %s' % (map_geometry_shape, self.map_geometry.size,))
223           for y, line in self.map.lines():
224               write(f, 'MAP_LINE %5s %s' % (y, quote(line)))
225           for yx in self.annotations:
226               write(f, 'GOD_ANNOTATE %s %s' % (yx, quote(self.annotations[yx])))
227           for yx in self.portals:
228               write(f, 'GOD_PORTAL %s %s' % (yx, quote(self.portals[yx])))
229           for y, line in self.map_control.lines():
230               write(f, 'MAP_CONTROL_LINE %5s %s' % (y, quote(line)))
231           for tile_class in self.map_control_passwords:
232               write(f, 'MAP_CONTROL_PW %s %s' % (tile_class,
233                                                  self.map_control_passwords[tile_class]))
234           for t in [t for t in self.things if not t.type_ == 'Player']:
235               write(f, 'THING %s %s %s' % (t.position, t.type_, t.id_))
236               if hasattr(t, 'name'):
237                   write(f, 'THING_NAME %s %s' % (t.id_, quote(t.name)))
238
239     def new_world(self, map_geometry):
240         self.map_geometry = map_geometry
241         self.map = Map(self.map_geometry.size)
242         self.map_control = Map(self.map_geometry.size)
243         self.annotations = {}