home · contact · privacy
Minor client improvements.
[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.commands import (cmd_ALL, cmd_LOGIN, cmd_QUERY, cmd_PING,
5                                 cmd_TURN, cmd_MAP_LINE, cmd_MAP, cmd_GET_ANNOTATION,
6                                 cmd_ANNOTATE, cmd_PORTAL, cmd_GET_GAMESTATE)
7 from plomrogue.io import GameIO
8 from plomrogue.misc import quote
9 from plomrogue.things import Thing, ThingPlayer
10 from plomrogue.mapping import YX, MapGeometrySquare, Map
11
12
13
14 class GameBase:
15
16     def __init__(self):
17         self.turn = 0
18         self.things = []
19
20     def get_thing(self, id_, create_unfound):
21         # No default for create_unfound because every call to get_thing
22         # should be accompanied by serious consideration whether to use it.
23         for thing in self.things:
24             if id_ == thing.id_:
25                 return thing
26         if create_unfound:
27             t = self.thing_type(self, id_)
28             self.things += [t]
29             return t
30         return None
31
32
33
34 class Game(GameBase):
35
36     def __init__(self, save_file, *args, **kwargs):
37         import os
38         super().__init__(*args, **kwargs)
39         self.changed = True
40         self.io = GameIO(self, save_file)
41         self.tasks = {'WAIT': Task_WAIT,
42                       'MOVE': Task_MOVE,
43                       'WRITE': Task_WRITE,
44                       'FLATTEN_SURROUNDINGS': Task_FLATTEN_SURROUNDINGS}
45         self.map_geometry = MapGeometrySquare(YX(24, 40))
46         self.commands = {'QUERY': cmd_QUERY,
47                          'ALL': cmd_ALL,
48                          'LOGIN': cmd_LOGIN,
49                          'TURN': cmd_TURN,
50                          'MAP_LINE': cmd_MAP_LINE,
51                          'GET_ANNOTATION': cmd_GET_ANNOTATION,
52                          'PORTAL': cmd_PORTAL,
53                          'GET_GAMESTATE': cmd_GET_GAMESTATE,
54                          'ANNOTATE': cmd_ANNOTATE,
55                          'MAP': cmd_MAP,
56                          'PING': cmd_PING}
57         self.thing_type = Thing
58         self.thing_types = {'player': ThingPlayer}
59         self.sessions = {}
60         self.map = Map(self.map_geometry.size)
61         self.annotations = {}
62         self.portals = {}
63         if os.path.exists(self.io.save_file):
64             if not os.path.isfile(self.io.save_file):
65                 raise GameError('save file path refers to non-file')
66             else:
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         if string_option_type == 'char':
79             return [c for c in
80                     string.digits + string.ascii_letters + string.punctuation + ' ']
81         return None
82
83     def send_gamestate(self, connection_id=None):
84         """Send out game state data relevant to clients."""
85
86         def send_thing(thing):
87             self.io.send('THING_POS %s %s' % (thing.id_, t.position))
88             if hasattr(thing, 'nickname'):
89                 self.io.send('THING_NAME %s %s' % (thing.id_, quote(t.nickname)))
90
91
92         self.io.send('TURN ' + str(self.turn))
93         for t in self.things:
94             send_thing(t)
95         self.io.send('MAP %s %s' % (self.map_geometry.size, quote(self.map.terrain)))
96         for yx in self.portals:
97             self.io.send('PORTAL %s %s' % (yx, quote(self.portals[yx])))
98         self.io.send('GAME_STATE_COMPLETE')
99
100     def run_tick(self):
101         to_delete = []
102         for connection_id in self.sessions:
103             connection_id_found = False
104             for server in self.io.servers:
105                 if connection_id in server.clients:
106                     connection_id_found = True
107                     break
108             if not connection_id_found:
109                 t = self.get_thing(self.sessions[connection_id], create_unfound=False)
110                 self.things.remove(t)
111                 to_delete += [connection_id]
112         for connection_id in to_delete:
113             del self.sessions[connection_id]
114             self.changed = True
115         for t in [t for t in self.things]:
116             if t in self.things:
117                 try:
118                     t.proceed()
119                 except GameError as e:
120                     for connection_id in [c_id for c_id in self.sessions
121                                           if self.sessions[c_id] == t.id_]:
122                         self.io.send('GAME_ERROR ' + quote(str(e)), connection_id)
123                 except PlayError as e:
124                     for connection_id in [c_id for c_id in self.sessions
125                                           if self.sessions[c_id] == t.id_]:
126                         self.io.send('PLAY_ERROR ' + quote(str(e)), connection_id)
127         if self.changed:
128             self.turn += 1
129             self.send_gamestate()
130             self.changed = False
131             self.save()
132
133     def get_command(self, command_name):
134
135         def partial_with_attrs(f, *args, **kwargs):
136             from functools import partial
137             p = partial(f, *args, **kwargs)
138             p.__dict__.update(f.__dict__)
139             return p
140
141         def cmd_TASK_colon(task_name, game, *args, connection_id):
142             if connection_id not in game.sessions:
143                 raise GameError('Not registered as player.')
144             t = game.get_thing(game.sessions[connection_id], create_unfound=False)
145             t.set_next_task(task_name, args)
146
147         def task_prefixed(command_name, task_prefix, task_command):
148             if command_name.startswith(task_prefix):
149                 task_name = command_name[len(task_prefix):]
150                 if task_name in self.tasks:
151                     f = partial_with_attrs(task_command, task_name, self)
152                     task = self.tasks[task_name]
153                     f.argtypes = task.argtypes
154                     return f
155             return None
156
157         command = task_prefixed(command_name, 'TASK:', cmd_TASK_colon)
158         if command:
159             return command
160         if command_name in self.commands:
161             f = partial_with_attrs(self.commands[command_name], self)
162             return f
163         return None
164
165     def new_thing_id(self):
166         if len(self.things) == 0:
167             return 0
168         # DANGEROUS – if anywhere we append a thing to the list of lower
169         # ID than the highest-value ID, this might lead to re-using an
170         # already active ID.  This condition /should/ not be fulfilled
171         # anywhere in the code, but if it does, trouble here is one of
172         # the more obvious indicators that it does – that's why there's
173         # no safeguard here against this.
174         return self.things[-1].id_ + 1
175
176     def save(self):
177
178       def write(f, msg):
179           f.write(msg + '\n')
180
181       with open(self.io.save_file, 'w') as f:
182           write(f, 'TURN %s' % self.turn)
183           write(f, 'MAP %s' % (self.map_geometry.size,))
184           for y, line in self.map.lines():
185               write(f, 'MAP_LINE %5s %s' % (y, quote(line)))
186           for yx in self.annotations:
187               write(f, 'ANNOTATE %s %s' % (yx, quote(self.annotations[yx])))
188           for yx in self.portals:
189               write(f, 'PORTAL %s %s' % (yx, quote(self.portals[yx])))
190
191     def new_world(self, size):
192         self.map_geometry = MapGeometrySquare(YX(size.y, size.x))
193         self.map = Map(self.map_geometry.size)
194         self.annotations = {}