home · contact · privacy
Add map writing.
[plomrogue2-experiments] / new2 / plomrogue / game.py
1 from plomrogue.tasks import Task_WAIT, Task_MOVE, Task_WRITE
2 from plomrogue.errors import GameError
3 from plomrogue.commands import cmd_ALL, cmd_LOGIN, cmd_QUERY
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         pass
15         self.turn = 0
16         self.things = []
17
18     def get_thing(self, id_, create_unfound):
19         # No default for create_unfound because every call to get_thing
20         # should be accompanied by serious consideration whether to use it.
21         for thing in self.things:
22             if id_ == thing.id_:
23                 return thing
24         if create_unfound:
25             t = self.thing_type(self, id_)
26             self.things += [t]
27             return t
28         return None
29
30
31
32 class Game(GameBase):
33
34     def __init__(self, *args, **kwargs):
35         super().__init__(*args, **kwargs)
36         self.changed = True
37         self.io = GameIO(self)
38         self.tasks = {'WAIT': Task_WAIT,
39                       'MOVE': Task_MOVE,
40                       'WRITE': Task_WRITE}
41         self.map_geometry = MapGeometrySquare(YX(24, 40))
42         self.commands = {'QUERY': cmd_QUERY,
43                          'ALL': cmd_ALL,
44                          'LOGIN': cmd_LOGIN}
45         self.thing_type = Thing
46         self.thing_types = {'player': ThingPlayer}
47         self.sessions = {}
48         self.map = Map(self.map_geometry.size)
49
50     def get_string_options(self, string_option_type):
51         import string
52         if string_option_type == 'direction':
53             return self.map_geometry.get_directions()
54         if string_option_type == 'char':
55             return [c for c in
56                     string.digits + string.ascii_letters + string.punctuation]
57         return None
58
59     def send_gamestate(self, connection_id=None):
60         """Send out game state data relevant to clients."""
61
62         def send_thing(thing):
63             self.io.send('THING_POS %s %s' % (thing.id_, t.position))
64
65         self.io.send('TURN ' + str(self.turn))
66         for t in self.things:
67             send_thing(t)
68         self.io.send('MAP %s %s' % (self.map_geometry.size, quote(self.map.terrain)))
69         self.io.send('GAME_STATE_COMPLETE')
70
71     def run_tick(self):
72         to_delete = []
73         for connection_id in self.sessions:
74             if not connection_id in self.io.server.clients:
75                 t = self.get_thing(self.sessions[connection_id], create_unfound=False)
76                 self.things.remove(t)
77                 to_delete += [connection_id]
78         for connection_id in to_delete:
79             del self.sessions[connection_id]
80             self.changed = True 
81         for t in [t for t in self.things]:
82             if t in self.things:
83                 try:
84                     t.proceed()
85                 except GameError as e:
86                     for connection_id in [c_id for c_id in self.sessions
87                                           if self.sessions[c_id] == t.id_]:
88                         self.io.send('GAME_ERROR ' + quote(str(e)), connection_id)
89         self.turn += 1
90         if self.changed:
91             self.send_gamestate()
92             self.changed = False
93
94     def get_command(self, command_name):
95
96         def partial_with_attrs(f, *args, **kwargs):
97             from functools import partial
98             p = partial(f, *args, **kwargs)
99             p.__dict__.update(f.__dict__)
100             return p
101
102         def cmd_TASK_colon(task_name, game, *args, connection_id):
103             if connection_id not in game.sessions:
104                 raise GameError('Not registered as player.')
105             t = game.get_thing(game.sessions[connection_id], create_unfound=False)
106             t.set_next_task(task_name, args)
107
108         def task_prefixed(command_name, task_prefix, task_command):
109             if command_name.startswith(task_prefix):
110                 task_name = command_name[len(task_prefix):]
111                 if task_name in self.tasks:
112                     f = partial_with_attrs(task_command, task_name, self)
113                     task = self.tasks[task_name]
114                     f.argtypes = task.argtypes
115                     return f
116             return None
117
118         command = task_prefixed(command_name, 'TASK:', cmd_TASK_colon)
119         if command:
120             return command
121         if command_name in self.commands:
122             f = partial_with_attrs(self.commands[command_name], self)
123             return f
124         return None
125
126     def new_thing_id(self):
127         if len(self.things) == 0:
128             return 0
129         # DANGEROUS – if anywhere we append a thing to the list of lower
130         # ID than the highest-value ID, this might lead to re-using an
131         # already active ID.  This condition /should/ not be fulfilled
132         # anywhere in the code, but if it does, trouble here is one of
133         # the more obvious indicators that it does – that's why there's
134         # no safeguard here against this.
135         return self.things[-1].id_ + 1