home · contact · privacy
Fix empty input bug in curses client.
[plomrogue2] / rogue_chat_curses.py
index 64eaf03959436cc768af00c0b323a7ab66f41259..acd6fa1719fb05a6329aeda2b81924419f65beb4 100755 (executable)
@@ -2,6 +2,7 @@
 import curses
 import queue
 import threading
+import time
 from plomrogue.game import GameBase
 from plomrogue.parser import Parser
 from plomrogue.mapping import YX, MapGeometrySquare, MapGeometryHex
@@ -103,11 +104,18 @@ def cmd_MAP(game, geometry, size, content):
         }
 cmd_MAP.argtypes = 'string:map_geometry yx_tuple:pos string'
 
+def cmd_FOV(game, content):
+    game.fov = content
+cmd_FOV.argtypes = 'string'
+
+def cmd_MAP_CONTROL(game, content):
+    game.map_control_content = content
+cmd_MAP_CONTROL.argtypes = 'string'
+
 def cmd_GAME_STATE_COMPLETE(game):
     game.info_db = {}
     if game.tui.mode.name == 'post_login_wait':
         game.tui.switch_mode('play')
-        game.tui.help()
     if game.tui.mode.shows_info:
         game.tui.query_info()
     player = game.get_thing(game.player_id, False)
@@ -166,6 +174,7 @@ class Game(GameBase):
         self.register_command(cmd_THING_POS)
         self.register_command(cmd_THING_NAME)
         self.register_command(cmd_MAP)
+        self.register_command(cmd_MAP_CONTROL)
         self.register_command(cmd_PORTAL)
         self.register_command(cmd_ANNOTATION)
         self.register_command(cmd_GAME_STATE_COMPLETE)
@@ -173,6 +182,7 @@ class Game(GameBase):
         self.register_command(cmd_GAME_ERROR)
         self.register_command(cmd_PLAY_ERROR)
         self.register_command(cmd_TASKS)
+        self.register_command(cmd_FOV)
         self.map_content = ''
         self.player_id = -1
         self.info_db = {}
@@ -193,27 +203,29 @@ class TUI:
 
     class Mode:
 
-        def __init__(self, name, has_input_prompt=False, shows_info=False,
-                     is_intro = False):
+        def __init__(self, name, help_intro, has_input_prompt=False,
+                     shows_info=False, is_intro = False):
             self.name = name
             self.has_input_prompt = has_input_prompt
             self.shows_info = shows_info
             self.is_intro = is_intro
+            self.help_intro = help_intro
 
     def __init__(self, host):
         import os
         import json
         self.host = host
-        self.mode_play = self.Mode('play')
-        self.mode_study = self.Mode('study', shows_info=True)
-        self.mode_edit = self.Mode('edit')
-        self.mode_annotate = self.Mode('annotate', has_input_prompt=True, shows_info=True)
-        self.mode_portal = self.Mode('portal', has_input_prompt=True, shows_info=True)
-        self.mode_chat = self.Mode('chat', has_input_prompt=True)
-        self.mode_waiting_for_server = self.Mode('waiting_for_server', is_intro=True)
-        self.mode_login = self.Mode('login', has_input_prompt=True, is_intro=True)
-        self.mode_post_login_wait = self.Mode('post_login_wait', is_intro=True)
-        self.mode_teleport = self.Mode('teleport', has_input_prompt=True)
+        self.mode_play = self.Mode('play', 'This mode allows you to interact with the map.')
+        self.mode_study = self.Mode('study', 'This mode allows you to study the map and its tiles in detail.  Move the question mark over a tile, and the right half of the screen will show detailed information on it.', shows_info=True)
+        self.mode_edit = self.Mode('edit', 'This mode allows you to change the map tile you currently stand on (if your map editing password authorizes you so).  Just enter any printable ASCII character to imprint it on the ground below you.')
+        self.mode_annotate = self.Mode('annotate', 'This mode allows you to add/edit a comment on the tile you are currently standing on (provided your map editing password authorizes you so).  Hit Return to leave.', has_input_prompt=True, shows_info=True)
+        self.mode_portal = self.Mode('portal', 'This mode allows you to imprint/edit/remove a teleportation target on the ground you are currently standing on (provided your map editing password authorizes you so).  Enter or edit a URL to imprint a teleportation target; enter emptiness to remove a pre-existing teleportation target.  Hit Return to leave.', has_input_prompt=True, shows_info=True)
+        self.mode_chat = self.Mode('chat', 'This mode allows you to engage in chit-chat with other users.  Any line you enter into the input prompt that does not start with a "/" will be sent to all users.  Lines that start with a "/" are used for commands like:', has_input_prompt=True)
+        self.mode_waiting_for_server = self.Mode('waiting_for_server', 'Waiting for a server response.', is_intro=True)
+        self.mode_login = self.Mode('login', 'Pick your player name.', has_input_prompt=True, is_intro=True)
+        self.mode_post_login_wait = self.Mode('post_login_wait', 'Waiting for a server response.', is_intro=True)
+        self.mode_teleport = self.Mode('teleport', 'Follow the instructions to re-connect and log-in to another server, or enter anything else to abort.', has_input_prompt=True)
+        self.mode_password = self.Mode('password', 'This mode allows you to change the password that you send to authorize yourself for editing password-protected map tiles.  Hit return to confirm and leave.', has_input_prompt=True)
         self.game = Game()
         self.game.tui = self
         self.parser = Parser(self.game)
@@ -221,15 +233,19 @@ class TUI:
         self.do_refresh = True
         self.queue = queue.Queue()
         self.login_name = None
+        self.map_mode = 'terrain'
+        self.password = 'foo'
         self.switch_mode('waiting_for_server')
         self.keys = {
             'switch_to_chat': 't',
             'switch_to_play': 'p',
-            'switch_to_annotate': 'm',
-            'switch_to_portal': 'P',
+            'switch_to_password': 'P',
+            'switch_to_annotate': 'M',
+            'switch_to_portal': 'T',
             'switch_to_study': '?',
             'switch_to_edit': 'm',
             'flatten': 'F',
+            'toggle_map_mode': 'M',
             'hex_move_upleft': 'w',
             'hex_move_upright': 'e',
             'hex_move_right': 'd',
@@ -246,11 +262,49 @@ class TUI:
                 keys_conf = json.loads(f.read())
             for k in keys_conf:
                 self.keys[k] = keys_conf[k]
+        self.show_help = False
+        self.disconnected = True
+        self.force_instant_connect = True
+        self.input_lines = []
+        self.fov = ''
         curses.wrapper(self.loop)
 
     def flash(self):
         curses.flash()
 
+    def connect(self):
+
+        def handle_recv(msg):
+            if msg == 'BYE':
+                self.socket.close()
+            else:
+                self.queue.put(msg)
+
+        self.log_msg('@ attempting connect')
+        socket_client_class = PlomSocketClient
+        if self.host.startswith('ws://') or self.host.startswith('wss://'):
+            socket_client_class = WebSocketClient
+        try:
+            self.socket = socket_client_class(handle_recv, self.host)
+            self.socket_thread = threading.Thread(target=self.socket.run)
+            self.socket_thread.start()
+            self.disconnected = False
+            self.socket.send('TASKS')
+            self.switch_mode('login')
+        except ConnectionRefusedError:
+            self.log_msg('@ server connect failure')
+            self.disconnected = True
+            self.switch_mode('waiting_for_server')
+        self.do_refresh = True
+
+    def reconnect(self):
+        self.log_msg('@ attempting reconnect')
+        self.send('QUIT')
+        time.sleep(0.1)  # FIXME necessitated by some some strange SSL race
+                         # conditions with ws4py, find out what exactly
+        self.switch_mode('waiting_for_server')
+        self.connect()
+
     def send(self, msg):
         try:
             if hasattr(self.socket, 'plom_closed') and self.socket.plom_closed:
@@ -258,6 +312,8 @@ class TUI:
             self.socket.send(msg)
         except (BrokenPipeError, BrokenSocketConnection):
             self.log_msg('@ server disconnected :(')
+            self.disconnected = True
+            self.force_instant_connect = True
             self.do_refresh = True
 
     def log_msg(self, msg):
@@ -268,13 +324,26 @@ class TUI:
     def query_info(self):
         self.send('GET_ANNOTATION ' + str(self.explorer))
 
-    def switch_mode(self, mode_name, keep_position = False):
+    def restore_input_values(self):
+        if self.mode.name == 'annotate' and self.explorer in self.game.info_db:
+            info = self.game.info_db[self.explorer]
+            if info != '(none)':
+                self.input_ = info
+        elif self.mode.name == 'portal' and self.explorer in self.game.portals:
+            self.input_ = self.game.portals[self.explorer]
+        elif self.mode.name == 'password':
+            self.input_ = self.password
+
+    def switch_mode(self, mode_name):
+        self.map_mode = 'terrain'
         self.mode = getattr(self, 'mode_' + mode_name)
-        if self.mode.shows_info and not keep_position:
+        if self.mode.shows_info:
             player = self.game.get_thing(self.game.player_id, False)
             self.explorer = YX(player.position.y, player.position.x)
         if self.mode.name == 'waiting_for_server':
             self.log_msg('@ waiting for server …')
+        if self.mode.name == 'edit':
+            self.show_help = True
         elif self.mode.name == 'login':
             if self.login_name:
                 self.send('LOGIN ' + quote(self.login_name))
@@ -283,39 +352,9 @@ class TUI:
         elif self.mode.name == 'teleport':
             self.log_msg("@ May teleport to %s" % (self.teleport_target_host)),
             self.log_msg("@ Enter 'YES!' to enthusiastically affirm.");
-        elif self.mode.name == 'annotate' and self.explorer in self.game.info_db:
-            info = self.game.info_db[self.explorer]
-            if info != '(none)':
-                self.input_ = info
-        elif self.mode.name == 'portal' and self.explorer in self.game.portals:
-            self.input_ = self.game.portals[self.explorer]
-
-    def help(self):
-        self.log_msg("HELP:");
-        self.log_msg("chat mode commands:");
-        self.log_msg("  /nick NAME - re-name yourself to NAME");
-        self.log_msg("  /msg USER TEXT - send TEXT to USER");
-        self.log_msg("  /help - show this help");
-        self.log_msg("  /%s or /play - switch to play mode" % self.keys['switch_to_play']);
-        self.log_msg("  /%s or /study - switch to study mode" % self.keys['switch_to_study']);
-        self.log_msg("commands common to study and play mode:");
-        if 'MOVE' in self.game.tasks:
-            self.log_msg("  %s - move" % ','.join(self.movement_keys));
-        self.log_msg("  %s - switch to chat mode" % self.keys['switch_to_chat']);
-        self.log_msg("commands specific to play mode:");
-        if 'WRITE' in self.game.tasks:
-            self.log_msg("  %s - write following ASCII character" % self.keys['switch_to_edit']);
-        if 'FLATTEN_SURROUNDINGS' in self.game.tasks:
-            self.log_msg("  %s - flatten surroundings" % self.keys['flatten']);
-        self.log_msg("  %s - switch to study mode" % self.keys['switch_to_study']);
-        self.log_msg("commands specific to study mode:");
-        if 'MOVE' not in self.game.tasks:
-            self.log_msg("  %s - move" % ','.join(self.movement_keys));
-        self.log_msg("  %s - annotate terrain" % self.keys['switch_to_annotate']);
-        self.log_msg("  %s - switch to play mode" % self.keys['switch_to_play']);
+        self.restore_input_values()
 
     def loop(self, stdscr):
-        import time
         import datetime
 
         def safe_addstr(y, x, line):
@@ -329,38 +368,6 @@ class TUI:
                 stdscr.insstr(y, self.size.x - 2, ' ')
                 stdscr.addstr(y, x, cut)
 
-        def connect():
-
-            def handle_recv(msg):
-                if msg == 'BYE':
-                    self.socket.close()
-                else:
-                    self.queue.put(msg)
-
-            socket_client_class = PlomSocketClient
-            if self.host.startswith('ws://') or self.host.startswith('wss://'):
-                socket_client_class = WebSocketClient
-            while True:
-                try:
-                    self.socket = socket_client_class(handle_recv, self.host)
-                    self.socket_thread = threading.Thread(target=self.socket.run)
-                    self.socket_thread.start()
-                    self.socket.send('TASKS')
-                    self.switch_mode('login')
-                    return
-                except ConnectionRefusedError:
-                    self.log_msg('@ server connect failure, trying again …')
-                    draw_screen()
-                    stdscr.refresh()
-                    time.sleep(1)
-
-        def reconnect():
-            self.send('QUIT')
-            time.sleep(0.1)  # FIXME necessitated by some some strange SSL race
-                             # conditions with ws4py, find out what exactly
-            self.switch_mode('waiting_for_server')
-            connect()
-
         def handle_input(msg):
             command, args = self.parser.parse(msg)
             command(*args)
@@ -417,18 +424,20 @@ class TUI:
             if not self.game.turn_complete:
                 return
             pos_i = self.explorer.y * self.game.map_geometry.size.x + self.explorer.x
-            info = 'TERRAIN: %s\n' % self.game.map_content[pos_i]
-            for t in self.game.things:
-                if t.position == self.explorer:
-                    info += 'PLAYER @: %s\n' % t.name
-            if self.explorer in self.game.portals:
-                info += 'PORTAL: ' + self.game.portals[self.explorer] + '\n'
-            else:
-                info += 'PORTAL: (none)\n'
-            if self.explorer in self.game.info_db:
-                info += 'ANNOTATION: ' + self.game.info_db[self.explorer]
-            else:
-                info += 'ANNOTATION: waiting …'
+            info = 'outside field of view'
+            if self.game.fov[pos_i] == '.':
+                info = 'TERRAIN: %s\n' % self.game.map_content[pos_i]
+                for t in self.game.things:
+                    if t.position == self.explorer:
+                        info += 'PLAYER @: %s\n' % t.name
+                if self.explorer in self.game.portals:
+                    info += 'PORTAL: ' + self.game.portals[self.explorer] + '\n'
+                else:
+                    info += 'PORTAL: (none)\n'
+                if self.explorer in self.game.info_db:
+                    info += 'ANNOTATION: ' + self.game.info_db[self.explorer]
+                else:
+                    info += 'ANNOTATION: waiting …'
             lines = msg_into_lines_of_width(info, self.window_width)
             height_header = 2
             for i in range(len(lines)):
@@ -449,18 +458,25 @@ class TUI:
             safe_addstr(0, self.window_width, 'TURN: ' + str(self.game.turn))
 
         def draw_mode():
-            safe_addstr(1, self.window_width, 'MODE: ' + self.mode.name)
+            help = "hit [%s] for help" % self.keys['help']
+            if self.mode.has_input_prompt:
+                help = "enter /help for help"
+            safe_addstr(1, self.window_width, 'MODE: %s – %s' % (self.mode.name, help))
 
         def draw_map():
             if not self.game.turn_complete:
                 return
             map_lines_split = []
+            map_content = self.game.map_content
+            if self.map_mode == 'control':
+                map_content = self.game.map_control_content
             for y in range(self.game.map_geometry.size.y):
                 start = self.game.map_geometry.size.x * y
                 end = start + self.game.map_geometry.size.x
-                map_lines_split += [list(self.game.map_content[start:end])]
-            for t in self.game.things:
-                map_lines_split[t.position.y][t.position.x] = '@'
+                map_lines_split += [list(map_content[start:end])]
+            if self.map_mode == 'terrain':
+                for t in self.game.things:
+                    map_lines_split[t.position.y][t.position.x] = '@'
             if self.mode.shows_info:
                 map_lines_split[self.explorer.y][self.explorer.x] = '?'
             map_lines = []
@@ -492,10 +508,52 @@ class TUI:
                 term_y += 1
                 map_y += 1
 
+        def draw_help():
+            content = "%s mode help\n\n%s\n\n" % (self.mode.name,
+                                                  self.mode.help_intro)
+            if self.mode == self.mode_play:
+                content += "Available actions:\n"
+                if 'MOVE' in self.game.tasks:
+                    content += "[%s] – move player\n" % ','.join(self.movement_keys)
+                if 'FLATTEN_SURROUNDINGS' in self.game.tasks:
+                    content += "[%s] – flatten player's surroundings\n" % self.keys['flatten']
+                content += 'Other modes available from here:\n'
+                content += '[%s] – chat mode\n' % self.keys['switch_to_chat']
+                content += '[%s] – study mode\n' % self.keys['switch_to_study']
+                content += '[%s] – terrain edit mode\n' % self.keys['switch_to_edit']
+                content += '[%s] – portal edit mode\n' % self.keys['switch_to_portal']
+                content += '[%s] – annotation mode\n' % self.keys['switch_to_annotate']
+                content += '[%s] – password input mode\n' % self.keys['switch_to_password']
+            elif self.mode == self.mode_study:
+                content += 'Available actions:\n'
+                content += '[%s] – move question mark\n' % ','.join(self.movement_keys)
+                content += '[%s] – toggle view between terrain, and password protection areas\n' % self.keys['toggle_map_mode']
+                content += '\n\nOther modes available from here:'
+                content += '[%s] – chat mode\n' % self.keys['switch_to_chat']
+                content += '[%s] – play mode\n' % self.keys['switch_to_play']
+            elif self.mode == self.mode_chat:
+                content += '/nick NAME – re-name yourself to NAME\n'
+                content += '/msg USER TEXT – send TEXT to USER\n'
+                content += '/%s or /play – switch to play mode\n' % self.keys['switch_to_play']
+                content += '/%s or /study – switch to study mode\n' % self.keys['switch_to_study']
+            for i in range(self.size.y):
+                safe_addstr(i,
+                            self.window_width * (not self.mode.has_input_prompt),
+                            ' '*self.window_width)
+            lines = []
+            for line in content.split('\n'):
+                lines += msg_into_lines_of_width(line, self.window_width)
+            for i in range(len(lines)):
+                if i >= self.size.y:
+                    break
+                safe_addstr(i,
+                            self.window_width * (not self.mode.has_input_prompt),
+                            lines[i])
+
         def draw_screen():
             stdscr.clear()
-            recalc_input_lines()
             if self.mode.has_input_prompt:
+                recalc_input_lines()
                 draw_input()
             if self.mode.shows_info:
                 draw_info()
@@ -505,6 +563,8 @@ class TUI:
             if not self.mode.is_intro:
                 draw_turn()
                 draw_map()
+            if self.show_help:
+                draw_help()
 
         curses.curs_set(False)  # hide cursor
         curses.use_default_colors();
@@ -513,13 +573,18 @@ class TUI:
         self.explorer = YX(0, 0)
         self.input_ = ''
         input_prompt = '> '
-        connect()
-        last_ping = datetime.datetime.now()
-        interval = datetime.timedelta(seconds=30)
+        interval = datetime.timedelta(seconds=5)
+        last_ping = datetime.datetime.now() - interval
         while True:
+            if self.disconnected and self.force_instant_connect:
+                self.force_instant_connect = False
+                self.connect()
             now = datetime.datetime.now()
             if now - last_ping > interval:
-                self.send('PING')
+                if self.disconnected:
+                    self.connect()
+                else:
+                    self.send('PING')
                 last_ping = now
             if self.do_refresh:
                 draw_screen()
@@ -535,29 +600,40 @@ class TUI:
                 self.do_refresh = True
             except curses.error:
                 continue
+            self.show_help = False
             if key == 'KEY_RESIZE':
                 reset_screen_size()
             elif self.mode.has_input_prompt and key == 'KEY_BACKSPACE':
                 self.input_ = self.input_[:-1]
+            elif self.mode.has_input_prompt and key == '\n' and self.input_ == '/help':
+                self.show_help = True
+                self.input_ = ""
+                self.restore_input_values()
             elif self.mode.has_input_prompt and key != '\n':  # Return key
                 self.input_ += key
                 max_length = self.window_width * self.size.y - len(input_prompt) - 1
                 if len(self.input_) > max_length:
                     self.input_ = self.input_[:max_length]
+            elif key == self.keys['help'] and self.mode != self.mode_edit:
+                self.show_help = True
             elif self.mode == self.mode_login and key == '\n':
                 self.login_name = self.input_
                 self.send('LOGIN ' + quote(self.input_))
                 self.input_ = ""
+            elif self.mode == self.mode_password and key == '\n':
+                if self.input_ == '':
+                    self.input_ = ' '
+                self.password = self.input_
+                self.input_ = ""
+                self.switch_mode('play')
             elif self.mode == self.mode_chat and key == '\n':
-                if self.input_[0] == '/':
+                if self.input_ == '':
+                    continue
+                if self.input_[0] == '/':  # FIXME fails on empty input
                     if self.input_ in {'/' + self.keys['switch_to_play'], '/play'}:
                         self.switch_mode('play')
                     elif self.input_ in {'/' + self.keys['switch_to_study'], '/study'}:
                         self.switch_mode('study')
-                    elif self.input_ == '/help':
-                        self.help()
-                    elif self.input_ == '/reconnect':
-                        reconnect()
                     elif self.input_.startswith('/nick'):
                         tokens = self.input_.split(maxsplit=1)
                         if len(tokens) == 2:
@@ -579,19 +655,21 @@ class TUI:
             elif self.mode == self.mode_annotate and key == '\n':
                 if self.input_ == '':
                     self.input_ = ' '
-                self.send('ANNOTATE %s %s' % (self.explorer, quote(self.input_)))
+                self.send('ANNOTATE %s %s %s' % (self.explorer, quote(self.input_),
+                                                 quote(self.password)))
                 self.input_ = ""
-                self.switch_mode('study', keep_position=True)
+                self.switch_mode('play')
             elif self.mode == self.mode_portal and key == '\n':
                 if self.input_ == '':
                     self.input_ = ' '
-                self.send('PORTAL %s %s' % (self.explorer, quote(self.input_)))
+                self.send('PORTAL %s %s %s' % (self.explorer, quote(self.input_),
+                                               quote(self.password)))
                 self.input_ = ""
-                self.switch_mode('study', keep_position=True)
+                self.switch_mode('play')
             elif self.mode == self.mode_teleport and key == '\n':
                 if self.input_ == 'YES!':
                     self.host = self.teleport_target_host
-                    reconnect()
+                    self.reconnect()
                 else:
                     self.log_msg('@ teleport aborted')
                     self.switch_mode('play')
@@ -601,10 +679,11 @@ class TUI:
                     self.switch_mode('chat')
                 elif key == self.keys['switch_to_play']:
                     self.switch_mode('play')
-                elif key == self.keys['switch_to_annotate']:
-                    self.switch_mode('annotate', keep_position=True)
-                elif key == self.keys['switch_to_portal']:
-                    self.switch_mode('portal', keep_position=True)
+                elif key == self.keys['toggle_map_mode']:
+                    if self.map_mode == 'terrain':
+                        self.map_mode = 'control'
+                    else:
+                        self.map_mode = 'terrain'
                 elif key in self.movement_keys:
                     move_explorer(self.movement_keys[key])
             elif self.mode == self.mode_play:
@@ -612,16 +691,22 @@ class TUI:
                     self.switch_mode('chat')
                 elif key == self.keys['switch_to_study']:
                     self.switch_mode('study')
+                elif key == self.keys['switch_to_annotate']:
+                    self.switch_mode('annotate')
+                elif key == self.keys['switch_to_portal']:
+                    self.switch_mode('portal')
+                elif key == self.keys['switch_to_password']:
+                    self.switch_mode('password')
                 if key == self.keys['switch_to_edit'] and\
                    'WRITE' in self.game.tasks:
                     self.switch_mode('edit')
                 elif key == self.keys['flatten'] and\
                      'FLATTEN_SURROUNDINGS' in self.game.tasks:
-                    self.send('TASK:FLATTEN_SURROUNDINGS')
+                    self.send('TASK:FLATTEN_SURROUNDINGS ' + quote(self.password))
                 elif key in self.movement_keys and 'MOVE' in self.game.tasks:
                     self.send('TASK:MOVE ' + self.movement_keys[key])
             elif self.mode == self.mode_edit:
-                self.send('TASK:WRITE ' + key)
+                self.send('TASK:WRITE %s %s' % (key, quote(self.password)))
                 self.switch_mode('play')
 
 TUI('localhost:5000')