home · contact · privacy
Register game commands and tasks outside of game module.
[plomrogue2-experiments] / new2 / 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.annotations = {}
53         self.portals = {}
54         if os.path.exists(self.io.save_file):
55             if not os.path.isfile(self.io.save_file):
56                 raise GameError('save file path refers to non-file')
57
58     def register_task(self, task):
59         prefix = 'Task_'
60         if not task.__name__.startswith(prefix):
61            raise GameError('illegal task object name: %s' % task.__name__)
62         task_name = task.__name__[len(prefix):]
63         self.tasks[task_name] = task
64
65     def read_savefile(self):
66         if os.path.exists(self.io.save_file):
67             with open(self.io.save_file, 'r') as f:
68                 lines = f.readlines()
69             for i in range(len(lines)):
70                 line = lines[i]
71                 print("FILE INPUT LINE %5s: %s" % (i, line), end='')
72                 self.io.handle_input(line, god_mode=True)
73
74     def get_string_options(self, string_option_type):
75         import string
76         if string_option_type == 'direction':
77             return self.map_geometry.get_directions()
78         elif string_option_type == 'char':
79             return [c for c in
80                     string.digits + string.ascii_letters + string.punctuation + ' ']
81         elif string_option_type == 'map_geometry':
82             return ['Hex', 'Square']
83         return None
84
85     def get_map_geometry_shape(self):
86         return self.map_geometry.__class__.__name__[len('MapGeometry'):]
87
88     def send_gamestate(self, connection_id=None):
89         """Send out game state data relevant to clients."""
90
91         def send_thing(thing):
92             self.io.send('THING_POS %s %s' % (thing.id_, t.position))
93             if hasattr(thing, 'nickname'):
94                 self.io.send('THING_NAME %s %s' % (thing.id_, quote(t.nickname)))
95
96         self.io.send('TURN ' + str(self.turn))
97         for t in self.things:
98             send_thing(t)
99         self.io.send('MAP %s %s %s' % (self.get_map_geometry_shape(),
100                                        self.map_geometry.size, quote(self.map.terrain)))
101         for yx in self.portals:
102             self.io.send('PORTAL %s %s' % (yx, quote(self.portals[yx])))
103         self.io.send('GAME_STATE_COMPLETE')
104
105     def run_tick(self):
106         to_delete = []
107         for connection_id in self.sessions:
108             connection_id_found = False
109             for server in self.io.servers:
110                 if connection_id in server.clients:
111                     connection_id_found = True
112                     break
113             if not connection_id_found:
114                 t = self.get_thing(self.sessions[connection_id], create_unfound=False)
115                 if hasattr(t, 'nickname'):
116                     self.io.send('CHAT ' + quote(t.nickname + ' left the map.'))
117                 self.things.remove(t)
118                 to_delete += [connection_id]
119         for connection_id in to_delete:
120             del self.sessions[connection_id]
121             self.changed = True
122         for t in [t for t in self.things]:
123             if t in self.things:
124                 try:
125                     t.proceed()
126                 except GameError as e:
127                     for connection_id in [c_id for c_id in self.sessions
128                                           if self.sessions[c_id] == t.id_]:
129                         self.io.send('GAME_ERROR ' + quote(str(e)), connection_id)
130                 except PlayError as e:
131                     for connection_id in [c_id for c_id in self.sessions
132                                           if self.sessions[c_id] == t.id_]:
133                         self.io.send('PLAY_ERROR ' + quote(str(e)), connection_id)
134         if self.changed:
135             self.turn += 1
136             self.send_gamestate()
137             self.changed = False
138             self.save()
139
140     def get_command(self, command_name):
141
142         def partial_with_attrs(f, *args, **kwargs):
143             from functools import partial
144             p = partial(f, *args, **kwargs)
145             p.__dict__.update(f.__dict__)
146             return p
147
148         def cmd_TASK_colon(task_name, game, *args, connection_id):
149             if connection_id not in game.sessions:
150                 raise GameError('Not registered as player.')
151             t = game.get_thing(game.sessions[connection_id], create_unfound=False)
152             t.set_next_task(task_name, args)
153
154         def task_prefixed(command_name, task_prefix, task_command):
155             if command_name.startswith(task_prefix):
156                 task_name = command_name[len(task_prefix):]
157                 if task_name in self.tasks:
158                     f = partial_with_attrs(task_command, task_name, self)
159                     task = self.tasks[task_name]
160                     f.argtypes = task.argtypes
161                     return f
162             return None
163
164         command = task_prefixed(command_name, 'TASK:', cmd_TASK_colon)
165         if command:
166             return command
167         if command_name in self.commands:
168             f = partial_with_attrs(self.commands[command_name], self)
169             return f
170         return None
171
172     def new_thing_id(self):
173         if len(self.things) == 0:
174             return 0
175         # DANGEROUS – if anywhere we append a thing to the list of lower
176         # ID than the highest-value ID, this might lead to re-using an
177         # already active ID.  This condition /should/ not be fulfilled
178         # anywhere in the code, but if it does, trouble here is one of
179         # the more obvious indicators that it does – that's why there's
180         # no safeguard here against this.
181         return self.things[-1].id_ + 1
182
183     def save(self):
184
185       def write(f, msg):
186           f.write(msg + '\n')
187
188       with open(self.io.save_file, 'w') as f:
189           # TODO: save tasks
190           write(f, 'TURN %s' % self.turn)
191           map_geometry_shape = self.get_map_geometry_shape()
192           write(f, 'MAP %s %s' % (map_geometry_shape, self.map_geometry.size,))
193           for y, line in self.map.lines():
194               write(f, 'MAP_LINE %5s %s' % (y, quote(line)))
195           for yx in self.annotations:
196               write(f, 'ANNOTATE %s %s' % (yx, quote(self.annotations[yx])))
197           for yx in self.portals:
198               write(f, 'PORTAL %s %s' % (yx, quote(self.portals[yx])))
199
200     def new_world(self, map_geometry):
201         self.map_geometry = map_geometry
202         self.map = Map(self.map_geometry.size)
203         self.annotations = {}