home · contact · privacy
47e08fb93c6257b0148cbc4768b837c4d85a37cb
[plomrogue2-experiments] / new2 / plomrogue / game.py
1 from plomrogue.tasks import Task_WAIT, Task_MOVE
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 MapGeometrySquare
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         self.map_geometry = MapGeometrySquare()
41         self.commands = {'QUERY': cmd_QUERY,
42                          'ALL': cmd_ALL,
43                          'LOGIN': cmd_LOGIN}
44         self.thing_type = Thing
45         self.thing_types = {'player': ThingPlayer}
46         self.sessions = {}
47
48     def get_string_options(self, string_option_type):
49         if string_option_type == 'direction':
50             return self.map_geometry.get_directions()
51         return None
52
53     def send_gamestate(self, connection_id=None):
54         """Send out game state data relevant to clients."""
55
56         def send_thing(thing):
57             self.io.send('THING_POS %s %s' % (thing.id_, t.position))
58
59         self.io.send('TURN ' + str(self.turn))
60         for t in self.things:
61             send_thing(t)
62         self.io.send('GAME_STATE_COMPLETE')
63
64     def run_tick(self):
65         to_delete = []
66         for connection_id in self.sessions:
67             if not connection_id in self.io.server.clients:
68                 t = self.get_thing(self.sessions[connection_id], create_unfound=False)
69                 self.things.remove(t)
70                 to_delete += [connection_id]
71         for connection_id in to_delete:
72             del self.sessions[connection_id]
73             self.changed = True 
74         for t in [t for t in self.things]:
75             if t in self.things:
76                 try:
77                     t.proceed()
78                 except GameError as e:
79                     for connection_id in [c_id for c_id in self.sessions
80                                           if self.sessions[c_id] == t.id_]:
81                         self.io.send('GAME_ERROR ' + quote(str(e)), connection_id)
82         self.turn += 1
83         if self.changed:
84             self.send_gamestate()
85             self.changed = False
86
87     def get_command(self, command_name):
88
89         def partial_with_attrs(f, *args, **kwargs):
90             from functools import partial
91             p = partial(f, *args, **kwargs)
92             p.__dict__.update(f.__dict__)
93             return p
94
95         def cmd_TASK_colon(task_name, game, *args, connection_id):
96             if connection_id not in game.sessions:
97                 raise GameError('Not registered as player.')
98             t = game.get_thing(game.sessions[connection_id], create_unfound=False)
99             t.set_next_task(task_name, args)
100
101         def task_prefixed(command_name, task_prefix, task_command):
102             if command_name.startswith(task_prefix):
103                 task_name = command_name[len(task_prefix):]
104                 if task_name in self.tasks:
105                     f = partial_with_attrs(task_command, task_name, self)
106                     task = self.tasks[task_name]
107                     f.argtypes = task.argtypes
108                     return f
109             return None
110
111         command = task_prefixed(command_name, 'TASK:', cmd_TASK_colon)
112         if command:
113             return command
114         if command_name in self.commands:
115             f = partial_with_attrs(self.commands[command_name], self)
116             return f
117         return None
118
119     def new_thing_id(self):
120         if len(self.things) == 0:
121             return 0
122         # DANGEROUS – if anywhere we append a thing to the list of lower
123         # ID than the highest-value ID, this might lead to re-using an
124         # already active ID.  This condition /should/ not be fulfilled
125         # anywhere in the code, but if it does, trouble here is one of
126         # the more obvious indicators that it does – that's why there's
127         # no safeguard here against this.
128         return self.things[-1].id_ + 1