home · contact · privacy
Refactor TUI drawing.
[plomrogue2-experiments] / new2 / rogue_chat_nocanvas_monochrome.html
index a3f81f2a0bf206ee5bdd81e767223d63feda45b5..e46daac50721239360c5259d52fad797eb7bb9a9 100644 (file)
@@ -11,8 +11,12 @@ let websocket_location = "ws://localhost:8000";
 let terminal = {
   rows: 24,
   cols: 80,
+  foreground: 'white',
+  background: 'black',
   initialize: function() {
     this.pre_el = document.getElementById("terminal");
+    this.pre_el.style.color = this.foreground;
+    this.pre_el.style.backgroundColor = this.background;
     this.content = [];
       let line = []
     for (let y = 0, x = 0; y <= this.rows; x++) {
@@ -28,6 +32,14 @@ let terminal = {
         line.push(' ');
     }
   },
+  blink_screen: function() {
+      this.pre_el.style.color = this.background;
+      this.pre_el.style.backgroundColor = this.foreground;
+      setTimeout(() => {
+          this.pre_el.style.color = this.foreground;
+          this.pre_el.style.backgroundColor = this.background;
+      }, 100);
+  },
   refresh: function() {
       let pre_string = '';
       for (let y = 0; y < this.rows; y++) {
@@ -44,15 +56,15 @@ let terminal = {
   drawBox: function(start_y, start_x, height, width) {
     let end_y = start_y + height;
     let end_x = start_x + width;
-      for (let y = start_y, x = start_x;; x++) {
-        if (x == end_x) {
-          x = start_x;
-          y += 1;
-          if (y == end_y) {
-              break;
-          }
-        };
-        this.content[y][x] = ' ';
+    for (let y = start_y, x = start_x; y < this.rows; x++) {
+      if (x == end_x) {
+        x = start_x;
+        y += 1;
+        if (y == end_y) {
+            break;
+        }
+      };
+      this.content[y][x] = ' ';
     }
   },
 }
@@ -112,11 +124,16 @@ let server = {
         this.websocket = new WebSocket(url);
         this.websocket.onopen = function(event) {
             window.setInterval(function() { server.send(['PING']) }, 30000);
-            server.send(['GET_GAMESTATE']);
+            tui.log_msg("@ server connected!");
+            tui.init_login();
         };
     },
     send: function(tokens) {
-        this.websocket.send(unparser.untokenize(tokens));
+        if (this.websocket.readyState !== WebSocket.OPEN) {
+            tui.log_msg('server disconnected :(');
+        } else {
+            this.websocket.send(unparser.untokenize(tokens));
+        }
     }
 }
 
@@ -145,27 +162,132 @@ let unparser = {
     }
 }
 
+class Mode {
+    constructor(name, has_input_prompt=false, shows_annotations=false, is_intro=false) {
+        this.name = name;
+        this.has_input_prompt = has_input_prompt;
+        this.shows_annotations = shows_annotations;
+        this.is_intro = is_intro;
+    }
+}
+let mode_waiting_for_server = new Mode('waiting_for_server', false, false, true);
+let mode_login = new Mode('login', true, false, true);
+let mode_chat = new Mode('chat', true, false);
+let mode_annotate = new Mode('annotate', true, true);
+let mode_play = new Mode('play', false, false);
+let mode_study = new Mode('study', false, true);
+let mode_edit = new Mode('edit', false, false);
+
 let tui = {
-  mode: 'chat',
+  mode: mode_waiting_for_server,
   log: [],
-  input_line: '',
-  switch_mode: function(mode_name, keep_pos=false) {
-    if (mode_name == 'study' && !keep_pos) {
+  input_prompt: '> ',
+  input: '',
+  input_lines: [],
+  window_width: terminal.cols / 2,
+  height_turn_line: 1,
+  height_mode_line: 1,
+  height_input: 1,
+  init: function() {
+      this.recalc_input_lines();
+      this.height_header = this.height_turn_line + this.height_mode_line;
+      this.log_msg("@ waiting for server connection ...");
+  },
+  init_login: function() {
+      this.log_msg("@ please enter your username:");
+      this.switch_mode(mode_login);
+  },
+  switch_mode: function(mode, keep_pos=false) {
+    if (mode == mode_study && !keep_pos) {
       explorer.position = game.things[game.player_id];
     }
-    this.mode = mode_name;
+    this.mode = mode;
+    this.empty_input();
+    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.full_refresh();
   },
-  draw_history: function() {
-    terminal.drawBox(1, terminal.cols / 2, terminal.rows - 2, terminal.cols / 2);
-    let i = 0;
-    for (let line of this.log) {
-      terminal.write(terminal.rows - 2 - i, terminal.cols / 2, line);
-      i += 1;
+  empty_input: function(str) {
+      this.input = "";
+      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.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 = [];
+    for (let i = 0, x = 0; i < msg.length; i++, x++) {
+      if (x >= width) {
+        lines.push(chunk);
+        chunk = "";
+        x = 0;
+      };
+      chunk += msg[i];
     }
+    lines.push(chunk);
+    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.shift();
+      };
+      this.full_refresh();
+  },
+  log_help: function() {
+    this.log_msg("");
+    this.log_msg("HELP");
+    this.log_msg("");
+    this.log_msg("chat mode commands:");
+    this.log_msg(":nick NAME - re-name yourself to NAME");
+    this.log_msg(":msg USER TEXT - send TEXT to USER");
+    this.log_msg(":help - show this help");
+    this.log_msg(":play or :p - switch to play mode");
+    this.log_msg(":study or :s - switch to study mode");
+    this.log_msg("");
+    this.log_msg("play mode commands:");
+    this.log_msg("w, a, s, d - move avatar");
+    this.log_msg("f - flatten surroundings");
+    this.log_msg("e - write following ASCII character");
+    this.log_msg("c - switch to chat mode");
+    this.log_msg("? - switch to study mode");
+    this.log_msg("");
+    this.log_msg("study mode commands:");
+    this.log_msg("w, a, s, d - move question mark");
+    this.log_msg("A - annotate terrain");
+    this.log_msg("c - switch to chat mode");
+    this.log_msg("p - switch to play mode");
+    this.log_msg("");
   },
   draw_map: function() {
-    terminal.drawBox(0, 0, terminal.rows, terminal.cols / 2);
     let map_lines = [];
     let line = [];
     for (let i = 0, j = 0; i < game.map.length; i++, j++) {
@@ -187,100 +309,68 @@ let tui = {
             center_pos = t;
         }
     };
-    if (tui.mode == 'study' || tui.mode == 'annotate') {
+    if (tui.mode.shows_annotations) {
         map_lines[explorer.position[0]][explorer.position[1]] = '?';
         center_pos = explorer.position;
     }
     let offset = [(terminal.rows / 2) - center_pos[0],
-                  terminal.cols / 4 - center_pos[1]];
+                  this.window_width / 2 - center_pos[1]];
       for (let term_y = offset[0], map_y = 0;
            term_y < terminal.rows && map_y < game.map_size[0];
            term_y++, map_y++) {
         if (term_y >= 0) {
-            let to_draw = map_lines[map_y].join('').slice(0, terminal.cols / 2 - offset[1]);
+            let to_draw = map_lines[map_y].join('').slice(0, this.window_width - offset[1]);
             terminal.write(term_y, offset[1], to_draw);
         }
     }
   },
+  draw_mode_line: function() {
+      terminal.write(0, this.window_width, 'MODE: ' + this.mode.name);
+  },
   draw_turn_line: function(n) {
-    terminal.drawBox(0, terminal.cols / 2, 1, terminal.cols / 2);
-    terminal.write(0, terminal.cols / 2, 'turn: ' + game.turn);
+    terminal.write(1, this.window_width, 'TURN: ' + game.turn);
   },
-  draw_input_line: function() {
-    terminal.drawBox(terminal.rows - 1, terminal.cols / 2, 1, terminal.cols / 2);
-    if (this.mode == 'chat' || this.mode == 'annotate') {
-      terminal.write(terminal.rows - 1, terminal.cols / 2, '> ' + this.input_line);
+  draw_history: function() {
+    if (terminal.rows <= this.height_header + this.height_input) {
+        return;
     }
+      for (let y = terminal.rows - 1 - this.height_input,
+               i = this.log.length - 1;
+           y >= this.height_header && i >= 0;
+           y--, i--) {
+          terminal.write(y, this.window_width, this.log[i]);
+      }
   },
-  msg_into_lines_of_width: function(msg, width) {
-    let chunk = "";
-    let lines = [];
-    for (let i = 0, x = 0; i < msg.length; i++, x++) {
-      if (x >= width) {
-        lines.unshift(chunk);
-        chunk = "";
-        x = 0;
-      };
-      chunk += msg[i];
+  draw_info: function() {
+    let lines = this.msg_into_lines_of_width(explorer.get_info(), this.window_width);
+    for (let y = this.height_header, i = 0; y < terminal.rows && i < lines.length; y++, i++) {
+      terminal.write(y, this.window_width, lines[i]);
     }
-    lines.unshift(chunk);
-    return lines;
   },
-  log_msg: function(msg) {
-    let line_length = (terminal.cols / 2);
-    let chunk = "";
-    this.log = this.msg_into_lines_of_width(msg, terminal.cols / 2).concat(this.log);
-    while (this.log.length > terminal.rows - 2) {
-      this.log.pop();
-    };
-    this.draw_history();
-  },
-  refresh: function() {
-    terminal.refresh();
-  },
-  log_help: function() {
-    tui.log_msg("");
-    tui.log_msg("HELP");
-    tui.log_msg("");
-    tui.log_msg("chat mode commands:");
-    tui.log_msg(":login USER - register as USER");
-    tui.log_msg(":msg USER TEXT - send TEXT to USER");
-    tui.log_msg(":help - show this help");
-    tui.log_msg(":play or :p - switch to play mode");
-    tui.log_msg(":study or :s - switch to study mode");
-    tui.log_msg("");
-    tui.log_msg("play mode commands:");
-    tui.log_msg("w, a, s, d - move avatar");
-    tui.log_msg("f - flatten surroundings");
-    tui.log_msg("e - write following ASCII character");
-    tui.log_msg("c - switch to chat mode");
-    tui.log_msg("? - switch to study mode");
-    tui.log_msg("");
-    tui.log_msg("study mode commands:");
-    tui.log_msg("w, a, s, d - move question mark");
-    tui.log_msg("A - annotate terrain");
-    tui.log_msg("c - switch to chat mode");
-    tui.log_msg("p - switch to play mode");
-    tui.log_msg("");
-  },
-  draw_info: function() {
-    terminal.drawBox(1, terminal.cols / 2, terminal.rows - 2, terminal.cols / 2);
-    let lines = this.msg_into_lines_of_width(explorer.get_info(), terminal.cols / 2);
-    lines.reverse();
-    for (let y = 1, i = 0; y < terminal.rows && i < lines.length; y++, i++) {
-      terminal.write(y, terminal.cols / 2, lines[i]);
+  draw_input: function() {
+    if (this.mode.has_input_prompt) {
+        for (let y = terminal.rows - this.height_input, i = 0; y < terminal.rows && i < this.input_lines.length; y++, i++) {
+            terminal.write(y, this.window_width, this.input_lines[i]);
+        }
     }
   },
   full_refresh: function() {
-    this.draw_map();
-    this.draw_turn_line();
-    if (this.mode == 'study' || this.mode == 'annotate') {
-      this.draw_info();
+    terminal.drawBox(0, 0, terminal.rows, terminal.cols);
+    if (this.mode.is_intro) {
+        this.draw_history();
+        this.draw_input();
     } else {
-      this.draw_history();
+        this.draw_map();
+        this.draw_turn_line();
+        this.draw_mode_line();
+        if (this.mode.shows_annotations) {
+          this.draw_info();
+        } else {
+          this.draw_history();
+        }
+        this.draw_input();
     }
-    this.draw_input_line();
-    this.refresh();
+    terminal.refresh();
   }
 }
 
@@ -293,7 +383,7 @@ let game = {
 }
 
 terminal.initialize();
-tui.log_help();
+tui.init();
 tui.full_refresh();
 
 server.init(websocket_location);
@@ -309,37 +399,36 @@ server.websocket.onmessage = function (event) {
     game.map = tokens[2]
   } else if (tokens[0] === 'GAME_STATE_COMPLETE') {
     explorer.empty_info_db();
-    if (tui.mode == 'study') {
+    if (tui.mode == mode_study) {
       explorer.query_info();
     }
-    tui.draw_turn_line();
-    tui.draw_map();
-    tui.refresh();
+    tui.full_refresh();
   } else if (tokens[0] === 'CHAT') {
      tui.log_msg('# ' + tokens[1], 1);
-     tui.refresh();
   } else if (tokens[0] === 'PLAYER_ID') {
       game.player_id = parseInt(tokens[1]);
   } else if (tokens[0] === 'META') {
      tui.log_msg('@ ' + tokens[1]);
-     tui.refresh();
+  } else if (tokens[0] === 'LOGIN_OK') {
+      server.send(['GET_GAMESTATE']);
+      tui.log_help();
+      tui.log_msg('@ ' + tokens[1]);
+      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');
-     tui.refresh();
+  } else if (tokens[0] === 'PLAY_ERROR') {
+     terminal.blink_screen();
   } else if (tokens[0] === 'ARGUMENT_ERROR') {
      tui.log_msg('? syntax error: ' + tokens[1]);
-     tui.refresh();
   } else if (tokens[0] === 'GAME_ERROR') {
      tui.log_msg('? game error: ' + tokens[1]);
-     tui.refresh();
   } else if (tokens[0] === 'PONG') {
     console.log('PONG');
   } else {
      tui.log_msg('? unhandled input: ' + event.data);
-     tui.refresh();
   }
 }
 
@@ -365,23 +454,19 @@ let explorer = {
             && !(try_pos[1] >= game.map_size[1])) {
             this.position = try_pos;
             this.query_info();
-            tui.draw_map();
-            tui.draw_info();
-            tui.refresh();
+            tui.full_refresh();
         }
     },
     update_info_db: function(yx, str) {
         this.info_db[yx] = str;
-        if (tui.mode == 'study') {
-            tui.draw_info();
-            tui.refresh();
+        if (tui.mode == mode_study) {
+            tui.full_refresh();
         }
     },
     empty_info_db: function() {
         this.info_db = {};
-        if (tui.mode == 'study') {
-            tui.draw_info();
-            tui.refresh();
+        if (tui.mode == mode_study) {
+            tui.full_refresh();
         }
     },
     query_info: function() {
@@ -403,60 +488,57 @@ let explorer = {
 }
 
 document.addEventListener('keydown', (event) => {
-    if (tui.mode == 'chat') {
-        if (event.key.length === 1) {
-            tui.input_line += event.key;
-            tui.draw_input_line();
-            tui.refresh();
-        } else if (event.key == 'Backspace') {
-            tui.input_line = tui.input_line.slice(0, -1);
-            tui.draw_input_line();
-            tui.refresh();
-        } else if (event.key == 'Enter') {
-            let [tokens, token_starts] = parser.tokenize(tui.input_line);
-            if (tokens.length > 0 && tokens[0].length > 0) {
-                if (tokens[0][0] == ':') {
-                    if (tokens[0] == ':play' || tokens[0] == ':p') {
-                        tui.switch_mode('play');
-                    } else if (tokens[0] == ':study' || tokens[0] == ':s') {
-                        tui.switch_mode('study');
-                    } else if (tokens[0] == ':help') {
-                        tui.log_help();
-                        tui.refresh();
-                    } else if (tokens[0] == ':login') {
-                        if (tokens.length > 1) {
-                            server.send(['LOGIN', tokens[1]]);
-                        } else {
-                            tui.log_msg('? need login name');
-                        }
-                    } else if (tokens[0] == ':msg') {
-                        if (tokens.length > 2) {
-                            let msg = tui.input_line.slice(token_starts[2]);
-                            server.send(['QUERY', tokens[1], msg]);
-                        } else {
-                            tui.log_msg('? need message target and message');
-                        }
+    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.switch_mode(mode_login);
+    } else if (tui.mode == mode_annotate && event.key == 'Enter') {
+        explorer.annotate(tui.input);
+        tui.switch_mode(mode_study, true);
+    } else if (tui.mode == mode_chat && event.key == 'Enter') {
+        let [tokens, token_starts] = parser.tokenize(tui.input);
+        if (tokens.length > 0 && tokens[0].length > 0) {
+            if (tokens[0][0] == ':') {
+                if (tokens[0] == ':play' || tokens[0] == ':p') {
+                    tui.switch_mode(mode_play);
+                } else if (tokens[0] == ':study' || tokens[0] == ':s') {
+                    tui.switch_mode(mode_study);
+                } else if (tokens[0] == ':help') {
+                    tui.log_help();
+                } else if (tokens[0] == ':nick') {
+                    if (tokens.length > 1) {
+                        server.send(['LOGIN', tokens[1]]);
+                    } else {
+                        tui.log_msg('? need login name');
+                    }
+                } else if (tokens[0] == ':msg') {
+                    if (tokens.length > 2) {
+                        let msg = tui.input.slice(token_starts[2]);
+                        server.send(['QUERY', tokens[1], msg]);
                     } else {
-                        tui.log_msg('? unknown command');
+                        tui.log_msg('? need message target and message');
                     }
                 } else {
-                    server.send(['ALL', tui.input_line]);
+                    tui.log_msg('? unknown command');
                 }
+            } else {
+                server.send(['ALL', tui.input]);
             }
-            tui.input_line = '';
-            tui.draw_input_line();
-            tui.refresh();
         }
-      } else if (tui.mode == 'play') {
+        tui.empty_input();
+        tui.full_refresh();
+      } else if (tui.mode == mode_play) {
           if (event.key === 'c') {
-              tui.switch_mode('chat');
+              tui.switch_mode(mode_chat);
           } else if (event.key === 'e') {
-              tui.switch_mode('edit');
+              tui.switch_mode(mode_edit);
           } else if (event.key === '?') {
-              tui.switch_mode('study');
+              tui.switch_mode(mode_study);
           } else if (event.key === 'F1') {
               tui.log_help();
-              tui.refresh();
           } else if (event.key === 'f') {
               server.send(["TASK:FLATTEN_SURROUNDINGS"]);
           } else if (event.key === 'a') {
@@ -468,16 +550,16 @@ document.addEventListener('keydown', (event) => {
           } else if (event.key === 's') {
               server.send(['TASK:MOVE', 'DOWN']);
           };
-    } else if (tui.mode == 'edit') {
+    } else if (tui.mode == mode_edit) {
         if (event.key != "Shift" && event.key.length == 1) {
             server.send(["TASK:WRITE", event.key]);
-            tui.switch_mode('play');
+            tui.switch_mode(mode_play);
         }
-    } else if (tui.mode == 'study') {
+    } else if (tui.mode == mode_study) {
         if (event.key === 'c') {
-            tui.switch_mode('chat');
+            tui.switch_mode(mode_chat);
         } else if (event.key == 'p') {
-            tui.switch_mode('play');
+            tui.switch_mode(mode_play);
         } else if (event.key === 'a') {
              explorer.move('left');
         } else if (event.key === 'd') {
@@ -487,24 +569,8 @@ document.addEventListener('keydown', (event) => {
         } else if (event.key === 's') {
              explorer.move('down');
         } else if (event.key === 'A') {
-          tui.switch_mode('annotate');
-          tui.draw_info();
-          tui.refresh();
+          tui.switch_mode(mode_annotate);
         };
-    } else if (tui.mode == 'annotate') {
-        if (event.key.length === 1) {
-            tui.input_line += event.key;
-            tui.draw_input_line();
-            tui.refresh();
-        } else if (event.key == 'Backspace') {
-            tui.input_line = tui.input_line.slice(0, -1);
-            tui.draw_input_line();
-            tui.refresh();
-        } else if (event.key == 'Enter') {
-            explorer.annotate(tui.input_line);
-            tui.input_line = '';
-            tui.switch_mode('study', true);
-        }
     }
 }, false);
 </script>