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