home · contact · privacy
Add field of view.
[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.things import Thing, ThingPlayer
7 from plomrogue.mapping import YX, MapGeometrySquare, Map
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_, create_unfound):
20         # No default for create_unfound because every call to get_thing
21         # should be accompanied by serious consideration whether to use it.
22         for thing in self.things:
23             if id_ == thing.id_:
24                 return thing
25         if create_unfound:
26             t = self.thing_type(self, id_)
27             self.things += [t]
28             return t
29         return None
30
31     def register_command(self, command):
32         prefix = 'cmd_'
33         if not command.__name__.startswith(prefix):
34            raise GameError('illegal command object name: %s' % command.__name__)
35         command_name = command.__name__[len(prefix):]
36         self.commands[command_name] = command
37
38
39
40 import os
41 class Game(GameBase):
42
43     def __init__(self, save_file, *args, **kwargs):
44         super().__init__(*args, **kwargs)
45         self.changed = True
46         self.io = GameIO(self, save_file)
47         self.tasks = {}
48         self.thing_type = Thing
49         self.thing_types = {'player': ThingPlayer}
50         self.sessions = {}
51         self.map = Map(self.map_geometry.size)
52         self.map_control = Map(self.map_geometry.size)
53         self.map_control_passwords = {}
54         self.annotations = {}
55         self.portals = {}
56         if os.path.exists(self.io.save_file):
57             if not os.path.isfile(self.io.save_file):
58                 raise GameError('save file path refers to non-file')
59
60     def register_task(self, task):
61         prefix = 'Task_'
62         if not task.__name__.startswith(prefix):
63            raise GameError('illegal task object name: %s' % task.__name__)
64         task_name = task.__name__[len(prefix):]
65         self.tasks[task_name] = task
66
67     def read_savefile(self):
68         if os.path.exists(self.io.save_file):
69             with open(self.io.save_file, 'r') as f:
70                 lines = f.readlines()
71             for i in range(len(lines)):
72                 line = lines[i]
73                 print("FILE INPUT LINE %5s: %s" % (i, line), end='')
74                 self.io.handle_input(line, god_mode=True)
75
76     def can_do_tile_with_pw(self, yx, pw):
77         tile_class = self.map_control[yx]
78         if tile_class in self.map_control_passwords:
79             tile_pw = self.map_control_passwords[tile_class]
80             if pw != tile_pw:
81                 return False
82         return True
83
84     def get_string_options(self, string_option_type):
85         import string
86         if string_option_type == 'direction':
87             return self.map_geometry.get_directions()
88         elif string_option_type == 'char':
89             return [c for c in
90                     string.digits + string.ascii_letters + string.punctuation + ' ']
91         elif string_option_type == 'map_geometry':
92             return ['Hex', 'Square']
93         return None
94
95     def get_map_geometry_shape(self):
96         return self.map_geometry.__class__.__name__[len('MapGeometry'):]
97
98     def send_gamestate(self, connection_id=None):
99         """Send out game state data relevant to clients."""
100
101         self.io.send('TURN ' + str(self.turn))
102         for c_id in self.sessions:
103             player = self.get_thing(self.sessions[c_id], create_unfound = False)
104             visible_terrain = player.fov_stencil_map(self.map)
105             self.io.send('FOV %s' % quote(player.fov_stencil.terrain), c_id)
106             self.io.send('MAP %s %s %s' % (self.get_map_geometry_shape(),
107                                            self.map_geometry.size,
108                                            quote(visible_terrain)), c_id)
109             visible_control = player.fov_stencil_map(self.map_control)
110             self.io.send('MAP_CONTROL %s' % quote(visible_control), c_id)
111             for t in [t for t in self.things
112                       if player.fov_stencil[t.position] == '.']:
113                 self.io.send('THING_POS %s %s' % (t.id_, t.position), c_id)
114                 if hasattr(t, 'nickname'):
115                     self.io.send('THING_NAME %s %s' % (t.id_,
116                                                        quote(t.nickname)), c_id)
117             for yx in [yx for yx in self.portals
118                        if player.fov_stencil[yx] == '.']:
119                 self.io.send('PORTAL %s %s' % (yx, quote(self.portals[yx])), c_id)
120         self.io.send('GAME_STATE_COMPLETE')
121
122     def run_tick(self):
123         to_delete = []
124         for connection_id in self.sessions:
125             connection_id_found = False
126             for server in self.io.servers:
127                 if connection_id in server.clients:
128                     connection_id_found = True
129                     break
130             if not connection_id_found:
131                 t = self.get_thing(self.sessions[connection_id], create_unfound=False)
132                 if hasattr(t, 'nickname'):
133                     self.io.send('CHAT ' + quote(t.nickname + ' left the map.'))
134                 self.things.remove(t)
135                 to_delete += [connection_id]
136         for connection_id in to_delete:
137             del self.sessions[connection_id]
138             self.changed = True
139         for t in [t for t in self.things]:
140             if t in self.things:
141                 try:
142                     t.proceed()
143                 except GameError 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('GAME_ERROR ' + quote(str(e)), connection_id)
147                 except PlayError as e:
148                     for connection_id in [c_id for c_id in self.sessions
149                                           if self.sessions[c_id] == t.id_]:
150                         self.io.send('PLAY_ERROR ' + quote(str(e)), connection_id)
151         if self.changed:
152             self.turn += 1
153             self.send_gamestate()
154             self.changed = False
155             self.save()
156
157     def get_command(self, command_name):
158
159         def partial_with_attrs(f, *args, **kwargs):
160             from functools import partial
161             p = partial(f, *args, **kwargs)
162             p.__dict__.update(f.__dict__)
163             return p
164
165         def cmd_TASK_colon(task_name, game, *args, connection_id):
166             if connection_id not in game.sessions:
167                 raise GameError('Not registered as player.')
168             t = game.get_thing(game.sessions[connection_id], create_unfound=False)
169             t.set_next_task(task_name, args)
170
171         def task_prefixed(command_name, task_prefix, task_command):
172             if command_name.startswith(task_prefix):
173                 task_name = command_name[len(task_prefix):]
174                 if task_name in self.tasks:
175                     f = partial_with_attrs(task_command, task_name, self)
176                     task = self.tasks[task_name]
177                     f.argtypes = task.argtypes
178                     return f
179             return None
180
181         command = task_prefixed(command_name, 'TASK:', cmd_TASK_colon)
182         if command:
183             return command
184         if command_name in self.commands:
185             f = partial_with_attrs(self.commands[command_name], self)
186             return f
187         return None
188
189     def new_thing_id(self):
190         if len(self.things) == 0:
191             return 0
192         # DANGEROUS – if anywhere we append a thing to the list of lower
193         # ID than the highest-value ID, this might lead to re-using an
194         # already active ID.  This condition /should/ not be fulfilled
195         # anywhere in the code, but if it does, trouble here is one of
196         # the more obvious indicators that it does – that's why there's
197         # no safeguard here against this.
198         return self.things[-1].id_ + 1
199
200     def save(self):
201
202       def write(f, msg):
203           f.write(msg + '\n')
204
205       with open(self.io.save_file, 'w') as f:
206           # TODO: save tasks
207           write(f, 'TURN %s' % self.turn)
208           map_geometry_shape = self.get_map_geometry_shape()
209           write(f, 'MAP %s %s' % (map_geometry_shape, self.map_geometry.size,))
210           for y, line in self.map.lines():
211               write(f, 'MAP_LINE %5s %s' % (y, quote(line)))
212           for yx in self.annotations:
213               write(f, 'GOD_ANNOTATE %s %s' % (yx, quote(self.annotations[yx])))
214           for yx in self.portals:
215               write(f, 'GOD_PORTAL %s %s' % (yx, quote(self.portals[yx])))
216           for y, line in self.map_control.lines():
217               write(f, 'MAP_CONTROL_LINE %5s %s' % (y, quote(line)))
218           for tile_class in self.map_control_passwords:
219               write(f, 'MAP_CONTROL_PW %s %s' % (tile_class,
220                                                  self.map_control_passwords[tile_class]))
221
222     def new_world(self, map_geometry):
223         self.map_geometry = map_geometry
224         self.map = Map(self.map_geometry.size)
225         self.map_control = Map(self.map_geometry.size)
226         self.annotations = {}