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