home · contact · privacy
Fix screen jumping around.
[plomrogue2-experiments] / new2 / rogue_chat_curses.py
1 #!/usr/bin/env python3
2 import curses
3 import socket
4 import queue
5 import threading
6 from plomrogue.io_tcp import PlomSocket
7 from plomrogue.game import GameBase
8 from plomrogue.parser import Parser
9 from plomrogue.mapping import YX
10 from plomrogue.things import ThingBase
11 from plomrogue.misc import quote
12
13 def cmd_TURN(game, n):
14     game.turn = n
15     game.things = []
16     game.portals = {}
17 cmd_TURN.argtypes = 'int:nonneg'
18
19 def cmd_LOGIN_OK(game):
20     game.tui.switch_mode('post_login_wait')
21     game.tui.socket.send('GET_GAMESTATE')
22     game.tui.log_msg('@ welcome')
23 cmd_LOGIN_OK.argtypes = ''
24
25 def cmd_CHAT(game, msg):
26     game.tui.log_msg('# ' + msg)
27     game.tui.do_refresh = True
28 cmd_CHAT.argtypes = 'string'
29
30 def cmd_PLAYER_ID(game, player_id):
31     game.player_id = player_id
32 cmd_PLAYER_ID.argtypes = 'int:nonneg'
33
34 def cmd_THING_POS(game, thing_id, position):
35     t = game.get_thing(thing_id, True)
36     t.position = position
37 cmd_THING_POS.argtypes = 'int:nonneg yx_tuple:nonneg'
38
39 def cmd_THING_NAME(game, thing_id, name):
40     t = game.get_thing(thing_id, True)
41     t.name = name
42 cmd_THING_NAME.argtypes = 'int:nonneg string'
43
44 def cmd_MAP(game, size, content):
45     game.map_size = size
46     game.map_content = content
47 cmd_MAP.argtypes = 'yx_tuple:pos string'
48
49 def cmd_GAME_STATE_COMPLETE(game):
50     game.info_db = {}
51     if game.tui.mode.name == 'post_login_wait':
52         game.tui.switch_mode('play')
53     if game.tui.mode.shows_info:
54         game.tui.query_info()
55     game.tui.do_refresh = True
56 cmd_GAME_STATE_COMPLETE.argtypes = ''
57
58 def cmd_PORTAL(game, position, msg):
59     game.portals[position] = msg
60 cmd_PORTAL.argtypes = 'yx_tuple:nonneg string'
61
62 def cmd_PLAY_ERROR(game, msg):
63     game.tui.log_msg('imagine the screen flicker (TODO)')
64     game.tui.do_refresh = True
65 cmd_PLAY_ERROR.argtypes = 'string'
66
67 def cmd_ARGUMENT_ERROR(game, msg):
68     game.tui.log_msg('? syntax error: ' + msg)
69     game.tui.do_refresh = True
70 cmd_ARGUMENT_ERROR.argtypes = 'string'
71
72 def cmd_ANNOTATION(game, position, msg):
73     game.info_db[position] = msg
74     if game.tui.mode.shows_info:
75         game.tui.do_refresh = True
76 cmd_ANNOTATION.argtypes = 'yx_tuple:nonneg string'
77
78 def recv_loop(plom_socket, q):
79     for msg in plom_socket.recv():
80         q.put(msg)
81
82 class Game(GameBase):
83     commands = {'LOGIN_OK': cmd_LOGIN_OK,
84                 'CHAT': cmd_CHAT,
85                 'PLAYER_ID': cmd_PLAYER_ID,
86                 'TURN': cmd_TURN,
87                 'THING_POS': cmd_THING_POS,
88                 'THING_NAME': cmd_THING_NAME,
89                 'MAP': cmd_MAP,
90                 'PORTAL': cmd_PORTAL,
91                 'ANNOTATION': cmd_ANNOTATION,
92                 'GAME_STATE_COMPLETE': cmd_GAME_STATE_COMPLETE,
93                 'ARGUMENT_ERROR': cmd_ARGUMENT_ERROR,
94                 'PLAY_ERROR': cmd_PLAY_ERROR}
95     thing_type = ThingBase
96
97     def __init__(self, *args, **kwargs):
98         super().__init__(*args, **kwargs)
99         self.map_size = YX(0, 0)
100         self.map_content = ''
101         self.player_id = -1
102         self.info_db = {}
103         self.portals = {}
104
105     def get_command(self, command_name):
106         from functools import partial
107         f = partial(self.commands[command_name], self)
108         f.argtypes = self.commands[command_name].argtypes
109         return f
110
111 class TUI:
112
113     def __init__(self, socket, q, game):
114         self.game = game
115         self.game.tui = self
116         self.parser = Parser(self.game)
117         self.queue = q
118         self.socket = socket
119         self.log = []
120         self.do_refresh = True
121         curses.wrapper(self.loop)
122
123     def log_msg(self, msg):
124         self.log += [msg]
125         if len(self.log) > 100:
126             self.log = self.log[-100:]
127
128     def query_info(self):
129         self.socket.send('GET_ANNOTATION ' + str(self.explorer))
130
131     def switch_mode(self, mode_name, keep_position = False):
132         self.mode = getattr(self, 'mode_' + mode_name)
133         if self.mode.shows_info and not keep_position:
134             player = self.game.get_thing(self.game.player_id, False)
135             self.explorer = YX(player.position.y, player.position.x)
136         if self.mode.name == 'annotate' and self.explorer in self.game.info_db:
137             info = self.game.info_db[self.explorer]
138             if info != '(none)':
139                 self.input_ = info
140         elif self.mode.name == 'portal' and self.explorer in self.game.portals:
141             self.input_ = self.game.portals[self.explorer]
142
143     def loop(self, stdscr):
144
145         class Mode:
146
147             def __init__(self, name, has_input_prompt=False, shows_info=False,
148                          is_intro = False):
149                 self.name = name
150                 self.has_input_prompt = has_input_prompt
151                 self.shows_info = shows_info
152                 self.is_intro = is_intro
153
154         def handle_input(msg):
155             command, args = self.parser.parse(msg)
156             command(*args)
157
158         def msg_into_lines_of_width(msg, width):
159             chunk = ''
160             lines = []
161             x = 0
162             for i in range(len(msg)):
163                 x += 1
164                 if x >= width or msg[i] == "\n":
165                     lines += [chunk]
166                     chunk = ''
167                     x = 0
168                 if msg[i] != "\n":
169                     chunk += msg[i]
170             lines += [chunk]
171             return lines
172
173         def reset_screen_size():
174             self.size = YX(*stdscr.getmaxyx())
175             self.size = self.size - YX(0, 1) # ugly TODO ncurses bug workaround, FIXME
176             self.size = self.size - YX(self.size.y % 2, 0)
177             self.size = self.size - YX(0, self.size.x % 4)
178             self.window_width = int(self.size.x / 2)
179
180         def recalc_input_lines():
181             if not self.mode.has_input_prompt:
182                 self.input_lines = []
183             else:
184                 self.input_lines = msg_into_lines_of_width(input_prompt + self.input_,
185                                                            self.window_width)
186
187         def move_explorer(direction):
188             # TODO movement constraints
189             if direction == 'up':
190                 self.explorer += YX(-1, 0)
191             elif direction == 'left':
192                 self.explorer += YX(0, -1)
193             elif direction == 'down':
194                 self.explorer += YX(1, 0)
195             elif direction == 'right':
196                 self.explorer += YX(0, 1)
197             self.query_info()
198
199         def draw_history():
200             lines = []
201             for line in self.log:
202                 lines += msg_into_lines_of_width(line, self.window_width)
203             lines.reverse()
204             height_header = 2
205             max_y = self.size.y - len(self.input_lines)
206             for i in range(len(lines)):
207                 if (i >= max_y - height_header):
208                     break
209                 stdscr.addstr(max_y - i - 1, self.window_width, lines[i])
210
211         def draw_info():
212             if self.explorer in self.game.portals:
213                 info = 'PORTAL: ' + self.game.portals[self.explorer] + '\n'
214             else:
215                 info = 'PORTAL: (none)\n'
216             if self.explorer in self.game.info_db:
217                 info += 'ANNOTATION: ' + self.game.info_db[self.explorer]
218             else:
219                 info += 'ANNOTATION: waiting …'
220             lines = msg_into_lines_of_width(info, self.window_width)
221             height_header = 2
222             for i in range(len(lines)):
223                 y = height_header + i
224                 if y >= self.size.y - len(self.input_lines):
225                     break
226                 stdscr.addstr(y, self.window_width, lines[i])
227
228         def draw_input():
229             y = self.size.y - len(self.input_lines)
230             for i in range(len(self.input_lines)):
231                 stdscr.addstr(y, self.window_width, self.input_lines[i])
232                 y += 1
233
234         def draw_turn():
235             stdscr.addstr(0, self.window_width, 'TURN: ' + str(self.game.turn))
236
237         def draw_mode():
238             stdscr.addstr(1, self.window_width, 'MODE: ' + self.mode.name)
239
240         def draw_map():
241             player = self.game.get_thing(self.game.player_id, False)
242             if not player:
243                 # catches race conditions where game.things still empty
244                 return
245             map_lines_split = []
246             for y in range(self.game.map_size.y):
247                 start = self.game.map_size.x * y
248                 end = start + self.game.map_size.x
249                 map_lines_split += [list(self.game.map_content[start:end])]
250             for t in self.game.things:
251                 map_lines_split[t.position.y][t.position.x] = '@'
252             if self.mode.shows_info:
253                 map_lines_split[self.explorer.y][self.explorer.x] = '?'
254             map_lines = []
255             for line in map_lines_split:
256                 map_lines += [''.join(line)]
257             map_center = YX(int(self.game.map_size.y / 2),
258                             int(self.game.map_size.x / 2))
259             window_center = YX(int(self.size.y / 2),
260                                int(self.window_width / 2))
261             center = player
262             if self.mode.shows_info:
263                 center = self.explorer
264             offset = center - window_center
265             term_y = max(0, -offset.y)
266             term_x = max(0, -offset.x)
267             map_y = max(0, offset.y)
268             map_x = max(0, offset.x)
269             while (term_y < self.size.y and map_y < self.game.map_size.y):
270                 to_draw = map_lines[map_y][map_x:self.window_width + offset.x]
271                 stdscr.addstr(term_y, term_x, to_draw)
272                 term_y += 1
273                 map_y += 1
274
275         def draw_screen():
276             stdscr.clear()
277             recalc_input_lines()
278             if self.mode.has_input_prompt:
279                 draw_input()
280             if self.mode.shows_info:
281                 draw_info()
282             else:
283                 draw_history()
284             draw_mode()
285             if not self.mode.is_intro:
286                 draw_turn()
287                 draw_map()
288
289         self.mode_play = Mode('play')
290         self.mode_study = Mode('study', shows_info=True)
291         self.mode_edit = Mode('edit')
292         self.mode_annotate = Mode('annotate', has_input_prompt=True, shows_info=True)
293         self.mode_portal = Mode('portal', has_input_prompt=True, shows_info=True)
294         self.mode_chat = Mode('chat', has_input_prompt=True)
295         self.mode_login = Mode('login', has_input_prompt=True, is_intro=True)
296         self.mode_post_login_wait = Mode('post_login_wait', is_intro=True)
297         curses.curs_set(False)  # hide cursor
298         stdscr.timeout(10)
299         reset_screen_size()
300         self.mode = self.mode_login
301         self.explorer = YX(0, 0)
302         self.input_ = ''
303         input_prompt = '> '
304         while True:
305             if self.do_refresh:
306                 draw_screen()
307                 self.do_refresh = False
308             while True:
309                 try:
310                     msg = self.queue.get(block=False)
311                     handle_input(msg)
312                 except queue.Empty:
313                     break
314             try:
315                 key = stdscr.getkey()
316                 self.do_refresh = True
317             except curses.error:
318                 continue
319             if key == 'KEY_RESIZE':
320                 reset_screen_size()
321             elif self.mode.has_input_prompt and key == 'KEY_BACKSPACE':
322                 self.input_ = self.input_[:-1]
323             elif self.mode.has_input_prompt and key != '\n':  # Return key
324                 self.input_ += key
325                 # TODO find out why - 1 is necessary here
326                 max_length = self.window_width * self.size.y - len(input_prompt) - 1
327                 if len(self.input_) > max_length:
328                     self.input_ = self.input_[:max_length]
329             elif self.mode == self.mode_login and key == '\n':
330                 self.socket.send('LOGIN ' + quote(self.input_))
331                 self.input_ = ""
332             elif self.mode == self.mode_chat and key == '\n':
333                 # TODO: query, nick, help, reconnect, unknown command
334                 if self.input_[0] == ':':
335                     if self.input_ in {':p', ':play'}:
336                         self.switch_mode('play')
337                     elif self.input_ in {':?', ':study'}:
338                         self.switch_mode('study')
339                     elif self.input_.startswith(':nick'):
340                         tokens = self.input_.split(maxsplit=1)
341                         if len(tokens) == 2:
342                             self.socket.send('LOGIN ' + quote(tokens[1]))
343                         else:
344                             self.log_msg('? need login name')
345                     elif self.input_.startswith(':msg'):
346                         tokens = self.input_.split(maxsplit=2)
347                         if len(tokens) == 3:
348                             self.socket.send('QUERY %s %s' % (quote(tokens[1]),
349                                                               quote(tokens[2])))
350                         else:
351                             self.log_msg('? need message target and message')
352                     else:
353                         self.log_msg('? unknown command')
354                 else:
355                     self.socket.send('ALL ' + quote(self.input_))
356                 self.input_ = ""
357             elif self.mode == self.mode_annotate and key == '\n':
358                 if (self.input_ == ''):
359                     self.input_ = ' '
360                 self.socket.send('ANNOTATE %s %s' % (self.explorer, quote(self.input_)))
361                 self.input_ = ""
362                 self.switch_mode('study', keep_position=True)
363             elif self.mode == self.mode_portal and key == '\n':
364                 if (self.input_ == ''):
365                     self.input_ = ' '
366                 self.socket.send('PORTAL %s %s' % (self.explorer, quote(self.input_)))
367                 self.input_ = ""
368                 self.switch_mode('study', keep_position=True)
369             elif self.mode == self.mode_study:
370                 if key == 'c':
371                     self.switch_mode('chat')
372                 elif key == 'p':
373                     self.switch_mode('play')
374                 elif key == 'A':
375                     self.switch_mode('annotate', keep_position=True)
376                 elif key == 'P':
377                     self.switch_mode('portal', keep_position=True)
378                 elif key == 'w':
379                     move_explorer('up')
380                 elif key == 'a':
381                     move_explorer('left')
382                 elif key == 's':
383                     move_explorer('down')
384                 elif key == 'd':
385                     move_explorer('right')
386             elif self.mode == self.mode_play:
387                 if key == 'c':
388                     self.switch_mode('chat')
389                 elif key == '?':
390                     self.switch_mode('study')
391                 if key == 'e':
392                     self.switch_mode('edit')
393                 elif key == 'f':
394                     self.socket.send('TASK:FLATTEN_SURROUNDINGS')
395                 elif key == 'w':
396                     self.socket.send('TASK:MOVE UP')
397                 elif key == 'a':
398                     self.socket.send('TASK:MOVE LEFT')
399                 elif key == 's':
400                     self.socket.send('TASK:MOVE DOWN')
401                 elif key == 'd':
402                     self.socket.send('TASK:MOVE RIGHT')
403             elif self.mode == self.mode_edit:
404                 self.socket.send('TASK:WRITE ' + key)
405                 self.switch_mode('play')
406
407 s = socket.create_connection(('127.0.0.1', 5000))
408 plom_socket = PlomSocket(s)
409 q = queue.Queue()
410 t = threading.Thread(target=recv_loop, args=(plom_socket, q))
411 t.start()
412 TUI(plom_socket, q, Game())