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