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