home · contact · privacy
Refactor client's server interaction code.
[plomrogue2-experiments] / new2 / rogue_chat_nocanvas_monochrome.html
index 09d400d8ca5c78eb6536fc042ffb10cf42de0a31..de79177a73c020781d6ac48ad8701c4a4bb1c36c 100644 (file)
@@ -3,23 +3,30 @@
 <style>
 </style>
 </head><body>
-<pre id="terminal" style="display: inline-block; color: white; background-color: black;"></pre>
 <div>
 movement: <select id="WASD_selector" name="WASD_selector" >
 <option value="w, a, s, d" selected>w, a, s, d</option>
 <option value="arrow keys">arrow keys</option>
 </select>
+rows: <input id="n_rows" type="number" step=2 min=10 value=24 />
+cols: <input id="n_cols" type="number" step=4 min=20 value=80 />
 </div>
+<pre id="terminal" style="display: inline-block;"></pre>
+<textarea id="input" style="opacity: 0; width: 0px;"></textarea>
 <script>
 "use strict";
 let websocket_location = "ws://localhost:8000";
 
+let wasd_selector = document.getElementById("WASD_selector");
+let rows_selector = document.getElementById("n_rows");
+let cols_selector = document.getElementById("n_cols");
+
 let terminal = {
-  rows: 24,
-  cols: 80,
   foreground: 'white',
   background: 'black',
   initialize: function() {
+    this.rows = rows_selector.value;
+    this.cols = cols_selector.value;
     this.pre_el = document.getElementById("terminal");
     this.pre_el.style.color = this.foreground;
     this.pre_el.style.backgroundColor = this.background;
@@ -74,6 +81,7 @@ let terminal = {
     }
   },
 }
+terminal.initialize();
 
 let parser = {
   tokenize: function(str) {
@@ -127,18 +135,60 @@ let parser = {
 
 let server = {
     init: function(url) {
-        this.websocket = new WebSocket(url);
+        this.url = url;
+        this.websocket = new WebSocket(this.url);
         this.websocket.onopen = function(event) {
             window.setInterval(function() { server.send(['PING']) }, 30000);
-            tui.log_msg("@ server connected!");
+            tui.log_msg("@ server connected! :)");
             tui.init_login();
         };
+        this.websocket.onclose = function(event) {
+            tui.log_msg('@ server disconnected :(');
+        };
+       this.websocket.onmessage = this.handle_event;
     },
     send: function(tokens) {
-        if (this.websocket.readyState !== WebSocket.OPEN) {
-            tui.log_msg('server disconnected :(');
+        this.websocket.send(unparser.untokenize(tokens));
+    },
+    handle_event: function(event) {
+        let tokens = parser.tokenize(event.data)[0];
+        if (tokens[0] === 'TURN') {
+            game.things = {}
+            game.turn = parseInt(tokens[1]);
+        } else if (tokens[0] === 'THING_POS') {
+            game.things[tokens[1]] = parser.parse_yx(tokens[2]);
+        } else if (tokens[0] === 'MAP') {
+            game.map_size = parser.parse_yx(tokens[1]);
+            game.map = tokens[2]
+        } else if (tokens[0] === 'GAME_STATE_COMPLETE') {
+            explorer.empty_info_db();
+            if (tui.mode == mode_study) {
+                explorer.query_info();
+            }
+            tui.full_refresh();
+        } else if (tokens[0] === 'CHAT') {
+             tui.log_msg('# ' + tokens[1], 1);
+        } else if (tokens[0] === 'PLAYER_ID') {
+            game.player_id = parseInt(tokens[1]);
+        } else if (tokens[0] === 'LOGIN_OK') {
+            this.send(['GET_GAMESTATE']);
+            tui.log_help();
+            tui.switch_mode(mode_play);
+        } else if (tokens[0] === 'ANNOTATION') {
+            let position = parser.parse_yx(tokens[1]);
+            explorer.update_info_db(position, tokens[2]);
+        } else if (tokens[0] === 'UNHANDLED_INPUT') {
+            tui.log_msg('? unknown command');
+        } else if (tokens[0] === 'PLAY_ERROR') {
+            terminal.blink_screen();
+        } else if (tokens[0] === 'ARGUMENT_ERROR') {
+            tui.log_msg('? syntax error: ' + tokens[1]);
+        } else if (tokens[0] === 'GAME_ERROR') {
+            tui.log_msg('? game error: ' + tokens[1]);
+        } else if (tokens[0] === 'PONG') {
+            console.log('PONG');
         } else {
-            this.websocket.send(unparser.untokenize(tokens));
+            tui.log_msg('? unhandled input: ' + event.data);
         }
     }
 }
@@ -148,7 +198,7 @@ let unparser = {
         let quoted = ['"'];
         for (let i = 0; i < str.length; i++) {
             let c = str[i];
-            if (c in ['"', '\\']) {
+            if (['"', '\\'].includes(c)) {
                 quoted.push('\\');
             };
             quoted.push(c);
@@ -188,36 +238,32 @@ let tui = {
   mode: mode_waiting_for_server,
   log: [],
   input_prompt: '> ',
-  input: '',
   input_lines: [],
   window_width: terminal.cols / 2,
   height_turn_line: 1,
   height_mode_line: 1,
   height_input: 1,
-  key_up: 'w',
-  key_down: 's',
-  key_left: 'a',
-  key_right: 'd',
-  movement_keys_desc: 'w, a, s, d',
   init: function() {
+      this.inputEl = document.getElementById("input");
+      this.inputEl.focus();
       this.recalc_input_lines();
       this.height_header = this.height_turn_line + this.height_mode_line;
       this.log_msg("@ waiting for server connection ...");
-      this.wasd_selector = document.getElementById("WASD_selector");
-      this.wasd_selector.addEventListener('input', function() {
-          if (tui.wasd_selector.value == 'w, a, s, d') {
-              tui.key_up = 'w';
-              tui.key_down = 's';
-              tui.key_left = 'a';
-              tui.key_right = 'd';
-          } else if (tui.wasd_selector.value == 'arrow keys') {
-              tui.key_up = 'ArrowUp';
-              tui.key_down = 'ArrowDown';
-              tui.key_left = 'ArrowLeft';
-              tui.key_right = 'ArrowRight';
-          };
-          tui.movement_keys_desc = tui.wasd_selector.value;
-      }, false);
+      this.init_wasd();
+  },
+  init_wasd: function() {
+    if (wasd_selector.value == 'w, a, s, d') {
+        tui.key_up = 'w';
+        tui.key_down = 's';
+        tui.key_left = 'a';
+        tui.key_right = 'd';
+    } else if (wasd_selector.value == 'arrow keys') {
+        tui.key_up = 'ArrowUp';
+        tui.key_down = 'ArrowDown';
+        tui.key_left = 'ArrowLeft';
+        tui.key_right = 'ArrowRight';
+    };
+    tui.movement_keys_desc = wasd_selector.value;
   },
   init_login: function() {
       this.log_msg("@ please enter your username:");
@@ -232,40 +278,24 @@ let tui = {
     if (mode == mode_annotate && explorer.position in explorer.info_db) {
         let info = explorer.info_db[explorer.position];
         if (info != "(none)") {
-            this.add_to_input(explorer.info_db[explorer.position]);
+           this.inputEl.value = explorer.info_db[explorer.position];
+           this.recalc_input_lines();
         }
     }
     this.full_refresh();
   },
   empty_input: function(str) {
-      this.input = "";
+      this.inputEl.value = "";
       if (this.mode.has_input_prompt) {
           this.recalc_input_lines();
       } else {
           this.height_input = 0;
       }
   },
-  add_to_input: function(str) {
-      if (this.input_prompt.length + this.input.length + str.length > this.window_width * terminal.rows) {
-          return;
-      }
-      this.input += str;
-      this.recalc_input_lines();
-      this.full_refresh();
-  },
   recalc_input_lines: function() {
-      this.input_lines = this.msg_into_lines_of_width(this.input_prompt + this.input, this.window_width);
+      this.input_lines = this.msg_into_lines_of_width(this.input_prompt + this.inputEl.value, this.window_width);
       this.height_input = this.input_lines.length;
   },
-  shorten_input: function() {
-      if (this.input.length == 0) {
-          terminal.blink_screen();
-      } else {
-          this.input = tui.input.slice(0, -1);
-          this.recalc_input_lines();
-          this.full_refresh();
-      }
-  },
   msg_into_lines_of_width: function(msg, width) {
     let chunk = "";
     let lines = [];
@@ -281,9 +311,8 @@ let tui = {
     return lines;
   },
   log_msg: function(msg) {
-      let lines = this.msg_into_lines_of_width(msg, this.window_width);
-      this.log = this.log.concat(lines);
-      while (this.log.length > terminal.rows) {
+      this.log.push(msg);
+      while (this.log.length > terminal.rows * 4) {
         this.log.shift();
       };
       this.full_refresh();
@@ -351,14 +380,15 @@ let tui = {
     terminal.write(1, this.window_width, 'TURN: ' + game.turn);
   },
   draw_history: function() {
-    if (terminal.rows <= this.height_header + this.height_input) {
-        return;
-    }
+      let log_display_lines = [];
+      for (let line of this.log) {
+          log_display_lines = log_display_lines.concat(this.msg_into_lines_of_width(line, this.window_width));
+      };
       for (let y = terminal.rows - 1 - this.height_input,
-               i = this.log.length - 1;
+               i = log_display_lines.length - 1;
            y >= this.height_header && i >= 0;
            y--, i--) {
-          terminal.write(y, this.window_width, this.log[i]);
+          terminal.write(y, this.window_width, log_display_lines[i]);
       }
   },
   draw_info: function() {
@@ -399,58 +429,12 @@ let game = {
   turn: 0,
   map: "",
   map_size: [0,0],
-  player_id: 0
+  player_id: -1
 }
 
-terminal.initialize();
 tui.init();
 tui.full_refresh();
-
 server.init(websocket_location);
-server.websocket.onmessage = function (event) {
-  let tokens = parser.tokenize(event.data)[0];
-  if (tokens[0] === 'TURN') {
-    game.things = {}
-    game.turn = parseInt(tokens[1]);
-  } else if (tokens[0] === 'THING_POS') {
-    game.things[tokens[1]] = parser.parse_yx(tokens[2]);
-  } else if (tokens[0] === 'MAP') {
-    game.map_size = parser.parse_yx(tokens[1]);
-    game.map = tokens[2]
-  } else if (tokens[0] === 'GAME_STATE_COMPLETE') {
-    explorer.empty_info_db();
-    if (tui.mode == mode_study) {
-      explorer.query_info();
-    }
-    tui.full_refresh();
-  } else if (tokens[0] === 'CHAT') {
-     tui.log_msg('# ' + tokens[1], 1);
-  } else if (tokens[0] === 'PLAYER_ID') {
-      game.player_id = parseInt(tokens[1]);
-  } else if (tokens[0] === 'META') {
-     tui.log_msg('@ ' + tokens[1]);
-  } else if (tokens[0] === 'LOGIN_OK') {
-      server.send(['GET_GAMESTATE']);
-      tui.log_msg('@ ' + tokens[1]);
-      tui.log_help();
-      tui.switch_mode(mode_chat);
-  } else if (tokens[0] === 'ANNOTATION') {
-     let position = parser.parse_yx(tokens[1]);
-     explorer.update_info_db(position, tokens[2]);
-  } else if (tokens[0] === 'UNHANDLED_INPUT') {
-     tui.log_msg('? unknown command');
-  } else if (tokens[0] === 'PLAY_ERROR') {
-     terminal.blink_screen();
-  } else if (tokens[0] === 'ARGUMENT_ERROR') {
-     tui.log_msg('? syntax error: ' + tokens[1]);
-  } else if (tokens[0] === 'GAME_ERROR') {
-     tui.log_msg('? game error: ' + tokens[1]);
-  } else if (tokens[0] === 'PONG') {
-    console.log('PONG');
-  } else {
-     tui.log_msg('? unhandled input: ' + event.data);
-  }
-}
 
 let explorer = {
     position: [0,0],
@@ -507,19 +491,31 @@ let explorer = {
     }
 }
 
-document.addEventListener('keydown', (event) => {
-    if (tui.mode.has_input_prompt && event.key.length === 1) {
-        tui.add_to_input(event.key);
-    } else if (tui.mode.has_input_prompt && event.key == 'Backspace') {
-        tui.shorten_input();
-    } else if (tui.mode == mode_login && event.key == 'Enter') {
-        server.send(['LOGIN', tui.input]);
+tui.inputEl.addEventListener('input', (event) => {
+    if (tui.mode.has_input_prompt) {
+       let max_length = tui.window_width * terminal.rows - tui.input_prompt.length;
+        if (tui.inputEl.value.length > max_length) {
+            tui.inputEl.value = tui.inputEl.value.slice(0, max_length);
+        };
+        tui.recalc_input_lines();
+        tui.full_refresh();
+    } else if (tui.mode == mode_edit && tui.inputEl.value.length > 0) {
+        server.send(["TASK:WRITE", tui.inputEl.value[0]]);
+        tui.switch_mode(mode_play);
+    }
+}, false);
+tui.inputEl.addEventListener('keydown', (event) => {
+    if (event.key == 'Enter') {
+       event.preventDefault();
+    }
+    if (tui.mode == mode_login && event.key == 'Enter') {
+        server.send(['LOGIN', tui.inputEl.value]);
         tui.switch_mode(mode_login);
     } else if (tui.mode == mode_annotate && event.key == 'Enter') {
-        explorer.annotate(tui.input);
+        explorer.annotate(tui.inputEl.value);
         tui.switch_mode(mode_study, true);
     } else if (tui.mode == mode_chat && event.key == 'Enter') {
-        let [tokens, token_starts] = parser.tokenize(tui.input);
+        let [tokens, token_starts] = parser.tokenize(tui.inputEl.value);
         if (tokens.length > 0 && tokens[0].length > 0) {
             if (tokens[0][0] == ':') {
                 if (tokens[0] == ':play' || tokens[0] == ':p') {
@@ -536,7 +532,7 @@ document.addEventListener('keydown', (event) => {
                     }
                 } else if (tokens[0] == ':msg') {
                     if (tokens.length > 2) {
-                        let msg = tui.input.slice(token_starts[2]);
+                        let msg = tui.inputEl.value.slice(token_starts[2]);
                         server.send(['QUERY', tokens[1], msg]);
                     } else {
                         tui.log_msg('? need message target and message');
@@ -544,16 +540,20 @@ document.addEventListener('keydown', (event) => {
                 } else {
                     tui.log_msg('? unknown command');
                 }
-            } else {
-                server.send(['ALL', tui.input]);
+           } else {
+               server.send(['ALL', tui.inputEl.value]);
             }
+       } else if (tui.inputEl.valuelength > 0) {
+           server.send(['ALL', tui.inputEl.value]);
         }
         tui.empty_input();
         tui.full_refresh();
       } else if (tui.mode == mode_play) {
           if (event.key === 'c') {
+              event.preventDefault();
               tui.switch_mode(mode_chat);
           } else if (event.key === 'e') {
+              event.preventDefault();
               tui.switch_mode(mode_edit);
           } else if (event.key === '?') {
               tui.switch_mode(mode_study);
@@ -570,28 +570,48 @@ document.addEventListener('keydown', (event) => {
           } else if (event.key === tui.key_down) {
               server.send(['TASK:MOVE', 'DOWN']);
           };
-    } else if (tui.mode == mode_edit) {
-        if (event.key != "Shift" && event.key.length == 1) {
-            server.send(["TASK:WRITE", event.key]);
-            tui.switch_mode(mode_play);
-        }
     } else if (tui.mode == mode_study) {
         if (event.key === 'c') {
             tui.switch_mode(mode_chat);
         } else if (event.key == 'p') {
             tui.switch_mode(mode_play);
-        } else if (event.key === 'a') {
-             explorer.move('left');
         } else if (event.key === tui.key_left) {
-             explorer.move('right');
+             explorer.move('left');
         } else if (event.key === tui.key_right) {
-             explorer.move('up');
+             explorer.move('right');
         } else if (event.key === tui.key_up) {
-             explorer.move('down');
+             explorer.move('up');
         } else if (event.key === tui.key_down) {
+             explorer.move('down');
+        } else if (event.key === 'e') {
+          event.preventDefault();
           tui.switch_mode(mode_annotate);
         };
     }
 }, false);
+
+wasd_selector.addEventListener('input', function() {
+    tui.init_wasd();
+}, false);
+rows_selector.addEventListener('input', function() {
+    if (rows_selector.value % 2 != 0) {
+        return;
+    }
+    terminal.initialize();
+    tui.full_refresh();
+}, false);
+cols_selector.addEventListener('input', function() {
+    if (cols_selector.value % 4 != 0) {
+        return;
+    }
+    terminal.initialize();
+    tui.window_width = terminal.cols / 2,
+    tui.full_refresh();
+}, false);
+window.setInterval(function() {
+    if (!(['input', 'n_cols', 'n_rows', 'WASD_selector'].includes(document.activeElement.id))) {
+        tui.inputEl.focus();
+    }
+}, 100);
 </script>
 </body></html>