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