home · contact · privacy
6fda713d2206ac3ed7d186586f0c0aaac542801f
[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, MapGeometrySquare, MapGeometryHex
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     game.turn_complete = False
18 cmd_TURN.argtypes = 'int:nonneg'
19
20 def cmd_LOGIN_OK(game):
21     game.tui.switch_mode('post_login_wait')
22     game.tui.send('GET_GAMESTATE')
23     game.tui.log_msg('@ welcome')
24 cmd_LOGIN_OK.argtypes = ''
25
26 def cmd_CHAT(game, msg):
27     game.tui.log_msg('# ' + msg)
28     game.tui.do_refresh = True
29 cmd_CHAT.argtypes = 'string'
30
31 def cmd_PLAYER_ID(game, player_id):
32     game.player_id = player_id
33 cmd_PLAYER_ID.argtypes = 'int:nonneg'
34
35 def cmd_THING_POS(game, thing_id, position):
36     t = game.get_thing(thing_id, True)
37     t.position = position
38 cmd_THING_POS.argtypes = 'int:nonneg yx_tuple:nonneg'
39
40 def cmd_THING_NAME(game, thing_id, name):
41     t = game.get_thing(thing_id, True)
42     t.name = name
43 cmd_THING_NAME.argtypes = 'int:nonneg string'
44
45 def cmd_MAP(game, geometry, size, content):
46     map_geometry_class = globals()['MapGeometry' + geometry]
47     game.map_geometry = map_geometry_class(size)
48     game.map_content = content
49     if type(game.map_geometry) == MapGeometrySquare:
50         game.tui.movement_keys = {
51             'w': 'UP',
52             'a': 'LEFT',
53             's': 'DOWN',
54             'd': 'RIGHT',
55         }
56     elif type(game.map_geometry) == MapGeometryHex:
57         game.tui.movement_keys = {
58             'w': 'UPLEFT',
59             'e': 'UPRIGHT',
60             'd': 'RIGHT',
61             'c': 'DOWNRIGHT',
62             'x': 'DOWNLEFT',
63             's': 'LEFT',
64         }
65 cmd_MAP.argtypes = 'string:map_geometry yx_tuple:pos string'
66
67 def cmd_GAME_STATE_COMPLETE(game):
68     game.info_db = {}
69     if game.tui.mode.name == 'post_login_wait':
70         game.tui.switch_mode('play')
71         game.tui.help()
72     if game.tui.mode.shows_info:
73         game.tui.query_info()
74     player = game.get_thing(game.player_id, False)
75     if player.position in game.portals:
76         #host, port = game.portals[player.position].split(':')
77         game.tui.teleport_target_host = game.portals[player.position]
78         game.tui.teleport_target_port = 5000
79         game.tui.switch_mode('teleport')
80     game.turn_complete = True
81     game.tui.do_refresh = True
82 cmd_GAME_STATE_COMPLETE.argtypes = ''
83
84 def cmd_PORTAL(game, position, msg):
85     game.portals[position] = msg
86 cmd_PORTAL.argtypes = 'yx_tuple:nonneg string'
87
88 def cmd_PLAY_ERROR(game, msg):
89     game.tui.flash()
90     game.tui.do_refresh = True
91 cmd_PLAY_ERROR.argtypes = 'string'
92
93 def cmd_GAME_ERROR(game, msg):
94     game.tui.log_msg('? game error: ' + msg)
95     game.tui.do_refresh = True
96 cmd_GAME_ERROR.argtypes = 'string'
97
98 def cmd_ARGUMENT_ERROR(game, msg):
99     game.tui.log_msg('? syntax error: ' + msg)
100     game.tui.do_refresh = True
101 cmd_ARGUMENT_ERROR.argtypes = 'string'
102
103 def cmd_ANNOTATION(game, position, msg):
104     game.info_db[position] = msg
105     if game.tui.mode.shows_info:
106         game.tui.do_refresh = True
107 cmd_ANNOTATION.argtypes = 'yx_tuple:nonneg string'
108
109 class Game(GameBase):
110     commands = {'LOGIN_OK': cmd_LOGIN_OK,
111                 'CHAT': cmd_CHAT,
112                 'PLAYER_ID': cmd_PLAYER_ID,
113                 'TURN': cmd_TURN,
114                 'THING_POS': cmd_THING_POS,
115                 'THING_NAME': cmd_THING_NAME,
116                 'MAP': cmd_MAP,
117                 'PORTAL': cmd_PORTAL,
118                 'ANNOTATION': cmd_ANNOTATION,
119                 'GAME_STATE_COMPLETE': cmd_GAME_STATE_COMPLETE,
120                 'ARGUMENT_ERROR': cmd_ARGUMENT_ERROR,
121                 'GAME_ERROR': cmd_GAME_ERROR,
122                 'PLAY_ERROR': cmd_PLAY_ERROR}
123     thing_type = ThingBase
124     turn_complete = False
125
126     def __init__(self, *args, **kwargs):
127         super().__init__(*args, **kwargs)
128         self.map_content = ''
129         self.player_id = -1
130         self.info_db = {}
131         self.portals = {}
132
133     def get_string_options(self, string_option_type):
134         if string_option_type == 'map_geometry':
135             return ['Hex', 'Square']
136         return None
137
138     def get_command(self, command_name):
139         from functools import partial
140         f = partial(self.commands[command_name], self)
141         f.argtypes = self.commands[command_name].argtypes
142         return f
143
144 class TUI:
145
146     class Mode:
147
148         def __init__(self, name, has_input_prompt=False, shows_info=False,
149                      is_intro = False):
150             self.name = name
151             self.has_input_prompt = has_input_prompt
152             self.shows_info = shows_info
153             self.is_intro = is_intro
154
155     def __init__(self, host, port):
156         self.host = host
157         self.port = port
158         self.mode_play = self.Mode('play')
159         self.mode_study = self.Mode('study', shows_info=True)
160         self.mode_edit = self.Mode('edit')
161         self.mode_annotate = self.Mode('annotate', has_input_prompt=True, shows_info=True)
162         self.mode_portal = self.Mode('portal', has_input_prompt=True, shows_info=True)
163         self.mode_chat = self.Mode('chat', has_input_prompt=True)
164         self.mode_waiting_for_server = self.Mode('waiting_for_server', is_intro=True)
165         self.mode_login = self.Mode('login', has_input_prompt=True, is_intro=True)
166         self.mode_post_login_wait = self.Mode('post_login_wait', is_intro=True)
167         self.mode_teleport = self.Mode('teleport', has_input_prompt=True)
168         self.game = Game()
169         self.game.tui = self
170         self.parser = Parser(self.game)
171         self.log = []
172         self.do_refresh = True
173         self.queue = queue.Queue()
174         self.login_name = None
175         self.switch_mode('waiting_for_server')
176         curses.wrapper(self.loop)
177
178     def flash(self):
179         curses.flash()
180
181     def send(self, msg):
182         try:
183             self.socket.send(msg)
184         except BrokenPipeError:
185             self.log_msg('@ server disconnected :(')
186             self.do_refresh = True
187
188     def log_msg(self, msg):
189         self.log += [msg]
190         if len(self.log) > 100:
191             self.log = self.log[-100:]
192
193     def query_info(self):
194         self.send('GET_ANNOTATION ' + str(self.explorer))
195
196     def switch_mode(self, mode_name, keep_position = False):
197         self.mode = getattr(self, 'mode_' + mode_name)
198         if self.mode.shows_info and not keep_position:
199             player = self.game.get_thing(self.game.player_id, False)
200             self.explorer = YX(player.position.y, player.position.x)
201         if self.mode.name == 'waiting_for_server':
202             self.log_msg('@ waiting for server …')
203         elif self.mode.name == 'login':
204             if self.login_name:
205                 self.send('LOGIN ' + quote(self.login_name))
206             else:
207                 self.log_msg('@ enter username')
208         elif self.mode.name == 'teleport':
209             self.log_msg("@ May teleport to %s:%s" % (self.teleport_target_host,
210                                                       self.teleport_target_port));
211             self.log_msg("@ Enter 'YES!' to enthusiastically affirm.");
212         elif self.mode.name == 'annotate' and self.explorer in self.game.info_db:
213             info = self.game.info_db[self.explorer]
214             if info != '(none)':
215                 self.input_ = info
216         elif self.mode.name == 'portal' and self.explorer in self.game.portals:
217             self.input_ = self.game.portals[self.explorer]
218
219     def help(self):
220         self.log_msg("HELP:");
221         self.log_msg("chat mode commands:");
222         self.log_msg("  :nick NAME - re-name yourself to NAME");
223         self.log_msg("  :msg USER TEXT - send TEXT to USER");
224         self.log_msg("  :help - show this help");
225         self.log_msg("  :p or :play - switch to play mode");
226         self.log_msg("  :? or :study - switch to study mode");
227         self.log_msg("commands common to study and play mode:");
228         self.log_msg("  w,a,s,d - move");
229         self.log_msg("  c - switch to chat mode");
230         self.log_msg("commands specific to play mode:");
231         self.log_msg("  e - write following ASCII character");
232         self.log_msg("  f - flatten surroundings");
233         self.log_msg("  ? - switch to study mode");
234         self.log_msg("commands specific to study mode:");
235         self.log_msg("  e - annotate terrain");
236         self.log_msg("  p - switch to play mode");
237
238     def loop(self, stdscr):
239
240         def safe_addstr(y, x, line):
241             if y < self.size.y - 1 or x + len(line) < self.size.x:
242                 stdscr.addstr(y, x, line)
243             else:  # workaround to <https://stackoverflow.com/q/7063128>
244                 cut_i = self.size.x - x - 1
245                 cut = line[:cut_i]
246                 last_char = line[cut_i]
247                 stdscr.addstr(y, self.size.x - 2, last_char)
248                 stdscr.insstr(y, self.size.x - 2, ' ')
249                 stdscr.addstr(y, x, cut)
250
251         def connect():
252             import time
253
254             def recv_loop():
255                 for msg in self.socket.recv():
256                     if msg == 'BYE':
257                         break
258                     self.queue.put(msg)
259
260             while True:
261                 try:
262                     s = socket.create_connection((self.host, self.port))
263                     self.socket = PlomSocket(s)
264                     self.socket_thread = threading.Thread(target=recv_loop)
265                     self.socket_thread.start()
266                     self.switch_mode('login')
267                     return
268                 except ConnectionRefusedError:
269                     self.log_msg('@ server connect failure, trying again …')
270                     draw_screen()
271                     stdscr.refresh()
272                     time.sleep(1)
273
274         def reconnect():
275             self.send('QUIT')
276             self.switch_mode('waiting_for_server')
277             connect()
278
279         def handle_input(msg):
280             command, args = self.parser.parse(msg)
281             command(*args)
282
283         def msg_into_lines_of_width(msg, width):
284             chunk = ''
285             lines = []
286             x = 0
287             for i in range(len(msg)):
288                 if x >= width or msg[i] == "\n":
289                     lines += [chunk]
290                     chunk = ''
291                     x = 0
292                 if msg[i] != "\n":
293                     chunk += msg[i]
294                 x += 1
295             lines += [chunk]
296             return lines
297
298         def reset_screen_size():
299             self.size = YX(*stdscr.getmaxyx())
300             self.size = self.size - YX(self.size.y % 2, 0)
301             self.size = self.size - YX(0, self.size.x % 4)
302             self.window_width = int(self.size.x / 2)
303
304         def recalc_input_lines():
305             if not self.mode.has_input_prompt:
306                 self.input_lines = []
307             else:
308                 self.input_lines = msg_into_lines_of_width(input_prompt + self.input_,
309                                                            self.window_width)
310
311         def move_explorer(direction):
312             target = self.game.map_geometry.move(self.explorer, direction)
313             if target:
314                 self.explorer = target
315                 self.query_info()
316             else:
317                 self.flash()
318
319         def draw_history():
320             lines = []
321             for line in self.log:
322                 lines += msg_into_lines_of_width(line, self.window_width)
323             lines.reverse()
324             height_header = 2
325             max_y = self.size.y - len(self.input_lines)
326             for i in range(len(lines)):
327                 if (i >= max_y - height_header):
328                     break
329                 safe_addstr(max_y - i - 1, self.window_width, lines[i])
330
331         def draw_info():
332             if not self.game.turn_complete:
333                 return
334             if self.explorer in self.game.portals:
335                 info = 'PORTAL: ' + self.game.portals[self.explorer] + '\n'
336             else:
337                 info = 'PORTAL: (none)\n'
338             if self.explorer in self.game.info_db:
339                 info += 'ANNOTATION: ' + self.game.info_db[self.explorer]
340             else:
341                 info += 'ANNOTATION: waiting …'
342             lines = msg_into_lines_of_width(info, self.window_width)
343             height_header = 2
344             for i in range(len(lines)):
345                 y = height_header + i
346                 if y >= self.size.y - len(self.input_lines):
347                     break
348                 safe_addstr(y, self.window_width, lines[i])
349
350         def draw_input():
351             y = self.size.y - len(self.input_lines)
352             for i in range(len(self.input_lines)):
353                 safe_addstr(y, self.window_width, self.input_lines[i])
354                 y += 1
355
356         def draw_turn():
357             if not self.game.turn_complete:
358                 return
359             safe_addstr(0, self.window_width, 'TURN: ' + str(self.game.turn))
360
361         def draw_mode():
362             safe_addstr(1, self.window_width, 'MODE: ' + self.mode.name)
363
364         def draw_map():
365             if not self.game.turn_complete:
366                 return
367             map_lines_split = []
368             for y in range(self.game.map_geometry.size.y):
369                 start = self.game.map_geometry.size.x * y
370                 end = start + self.game.map_geometry.size.x
371                 map_lines_split += [list(self.game.map_content[start:end])]
372             for t in self.game.things:
373                 map_lines_split[t.position.y][t.position.x] = '@'
374             if self.mode.shows_info:
375                 map_lines_split[self.explorer.y][self.explorer.x] = '?'
376             map_lines = []
377             if type(self.game.map_geometry) == MapGeometryHex:
378                 indent = 0
379                 for line in map_lines_split:
380                     map_lines += [indent*' ' + ' '.join(line)]
381                     indent = 0 if indent else 1
382             else:
383                 for line in map_lines_split:
384                     map_lines += [''.join(line)]
385             window_center = YX(int(self.size.y / 2),
386                                int(self.window_width / 2))
387             player = self.game.get_thing(self.game.player_id, False)
388             center = player.position
389             if self.mode.shows_info:
390                 center = self.explorer
391             if type(self.game.map_geometry) == MapGeometryHex:
392                 center = YX(center.y, center.x * 2)
393             offset = center - window_center
394             if type(self.game.map_geometry) == MapGeometryHex and offset.y % 2:
395                 offset += YX(0, 1)
396             term_y = max(0, -offset.y)
397             term_x = max(0, -offset.x)
398             map_y = max(0, offset.y)
399             map_x = max(0, offset.x)
400             while (term_y < self.size.y and map_y < self.game.map_geometry.size.y):
401                 to_draw = map_lines[map_y][map_x:self.window_width + offset.x]
402                 safe_addstr(term_y, term_x, to_draw)
403                 term_y += 1
404                 map_y += 1
405
406         def draw_screen():
407             stdscr.clear()
408             recalc_input_lines()
409             if self.mode.has_input_prompt:
410                 draw_input()
411             if self.mode.shows_info:
412                 draw_info()
413             else:
414                 draw_history()
415             draw_mode()
416             if not self.mode.is_intro:
417                 draw_turn()
418                 draw_map()
419
420         curses.curs_set(False)  # hide cursor
421         stdscr.timeout(10)
422         reset_screen_size()
423         self.explorer = YX(0, 0)
424         self.input_ = ''
425         input_prompt = '> '
426         connect()
427         while True:
428             if self.do_refresh:
429                 draw_screen()
430                 self.do_refresh = False
431             while True:
432                 try:
433                     msg = self.queue.get(block=False)
434                     handle_input(msg)
435                 except queue.Empty:
436                     break
437             try:
438                 key = stdscr.getkey()
439                 self.do_refresh = True
440             except curses.error:
441                 continue
442             if key == 'KEY_RESIZE':
443                 reset_screen_size()
444             elif self.mode.has_input_prompt and key == 'KEY_BACKSPACE':
445                 self.input_ = self.input_[:-1]
446             elif self.mode.has_input_prompt and key != '\n':  # Return key
447                 self.input_ += key
448                 max_length = self.window_width * self.size.y - len(input_prompt) - 1
449                 if len(self.input_) > max_length:
450                     self.input_ = self.input_[:max_length]
451             elif self.mode == self.mode_login and key == '\n':
452                 self.login_name = self.input_
453                 self.send('LOGIN ' + quote(self.input_))
454                 self.input_ = ""
455             elif self.mode == self.mode_chat and key == '\n':
456                 if self.input_[0] == ':':
457                     if self.input_ in {':p', ':play'}:
458                         self.switch_mode('play')
459                     elif self.input_ in {':?', ':study'}:
460                         self.switch_mode('study')
461                     if self.input_ == ':help':
462                         self.help()
463                     if self.input_ == ':reconnect':
464                         reconnect()
465                     elif self.input_.startswith(':nick'):
466                         tokens = self.input_.split(maxsplit=1)
467                         if len(tokens) == 2:
468                             self.send('LOGIN ' + quote(tokens[1]))
469                         else:
470                             self.log_msg('? need login name')
471                     elif self.input_.startswith(':msg'):
472                         tokens = self.input_.split(maxsplit=2)
473                         if len(tokens) == 3:
474                             self.send('QUERY %s %s' % (quote(tokens[1]),
475                                                               quote(tokens[2])))
476                         else:
477                             self.log_msg('? need message target and message')
478                     else:
479                         self.log_msg('? unknown command')
480                 else:
481                     self.send('ALL ' + quote(self.input_))
482                 self.input_ = ""
483             elif self.mode == self.mode_annotate and key == '\n':
484                 if self.input_ == '':
485                     self.input_ = ' '
486                 self.send('ANNOTATE %s %s' % (self.explorer, quote(self.input_)))
487                 self.input_ = ""
488                 self.switch_mode('study', keep_position=True)
489             elif self.mode == self.mode_portal and key == '\n':
490                 if self.input_ == '':
491                     self.input_ = ' '
492                 self.send('PORTAL %s %s' % (self.explorer, quote(self.input_)))
493                 self.input_ = ""
494                 self.switch_mode('study', keep_position=True)
495             elif self.mode == self.mode_teleport and key == '\n':
496                 if self.input_ == 'YES!':
497                     self.host = self.teleport_target_host
498                     self.port = self.teleport_target_port
499                     reconnect()
500                 else:
501                     self.log_msg('@ teleport aborted')
502                     self.switch_mode('play')
503                 self.input_ = ''
504             elif self.mode == self.mode_study:
505                 if key == 'C':
506                     self.switch_mode('chat')
507                 elif key == 'P':
508                     self.switch_mode('play')
509                 elif key == 'A':
510                     self.switch_mode('annotate', keep_position=True)
511                 elif key == 'p':
512                     self.switch_mode('portal', keep_position=True)
513                 elif key in self.movement_keys:
514                     move_explorer(self.movement_keys[key])
515             elif self.mode == self.mode_play:
516                 if key == 'C':
517                     self.switch_mode('chat')
518                 elif key == '?':
519                     self.switch_mode('study')
520                 if key == 'E':
521                     self.switch_mode('edit')
522                 elif key == 'f':
523                     self.send('TASK:FLATTEN_SURROUNDINGS')
524                 elif key in self.movement_keys:
525                     self.send('TASK:MOVE ' + self.movement_keys[key])
526             elif self.mode == self.mode_edit:
527                 self.send('TASK:WRITE ' + key)
528                 self.switch_mode('play')
529
530 TUI('127.0.0.1', 5000)