home · contact · privacy
Refactor TUI drawing.
[plomrogue2-experiments] / new2 / rogue_chat_nocanvas_monochrome.html
1 <!DOCTYPE html>
2 <html><head>
3 <style>
4 </style>
5 </head><body>
6 <pre id="terminal" style="display: inline-block; color: white; background-color: black;"></pre>
7 <script>
8 "use strict";
9 let websocket_location = "ws://localhost:8000";
10
11 let terminal = {
12   rows: 24,
13   cols: 80,
14   foreground: 'white',
15   background: 'black',
16   initialize: function() {
17     this.pre_el = document.getElementById("terminal");
18     this.pre_el.style.color = this.foreground;
19     this.pre_el.style.backgroundColor = this.background;
20     this.content = [];
21       let line = []
22     for (let y = 0, x = 0; y <= this.rows; x++) {
23         if (x == this.cols) {
24             x = 0;
25             y += 1;
26             this.content.push(line);
27             line = [];
28             if (y == this.rows) {
29                 break;
30             }
31         }
32         line.push(' ');
33     }
34   },
35   blink_screen: function() {
36       this.pre_el.style.color = this.background;
37       this.pre_el.style.backgroundColor = this.foreground;
38       setTimeout(() => {
39           this.pre_el.style.color = this.foreground;
40           this.pre_el.style.backgroundColor = this.background;
41       }, 100);
42   },
43   refresh: function() {
44       let pre_string = '';
45       for (let y = 0; y < this.rows; y++) {
46           let line = this.content[y].join('');
47           pre_string += line + '\n';
48       }
49       this.pre_el.textContent = pre_string;
50   },
51   write: function(start_y, start_x, msg) {
52       for (let x = start_x, i = 0; x < this.cols && i < msg.length; x++, i++) {
53           this.content[start_y][x] = msg[i];
54       }
55   },
56   drawBox: function(start_y, start_x, height, width) {
57     let end_y = start_y + height;
58     let end_x = start_x + width;
59     for (let y = start_y, x = start_x; y < this.rows; x++) {
60       if (x == end_x) {
61         x = start_x;
62         y += 1;
63         if (y == end_y) {
64             break;
65         }
66       };
67       this.content[y][x] = ' ';
68     }
69   },
70 }
71
72 let parser = {
73   tokenize: function(str) {
74     let token_ends = [];
75     let tokens = [];
76     let token = ''
77     let quoted = false;
78     let escaped = false;
79     for (let i = 0; i < str.length; i++) {
80       let c = str[i];
81       if (quoted) {
82         if (escaped) {
83           token += c;
84           escaped = false;
85         } else if (c == '\\') {
86           escaped = true;
87         } else if (c == '"') {
88           quoted = false
89         } else {
90           token += c;
91         }
92       } else if (c == '"') {
93         quoted = true
94       } else if (c === ' ') {
95         if (token.length > 0) {
96           token_ends.push(i);
97           tokens.push(token);
98           token = '';
99         }
100       } else {
101         token += c;
102       }
103     }
104     if (token.length > 0) {
105       tokens.push(token);
106     }
107     let token_starts = [];
108     for (let i = 0; i < token_ends.length; i++) {
109       token_starts.push(token_ends[i] - tokens[i].length);
110     };
111     return [tokens, token_starts];
112   },
113   parse_yx: function(position_string) {
114     let coordinate_strings = position_string.split(',')
115     let position = [0, 0];
116     position[0] = parseInt(coordinate_strings[0].slice(2));
117     position[1] = parseInt(coordinate_strings[1].slice(2));
118     return position;
119   },
120 }
121
122 let server = {
123     init: function(url) {
124         this.websocket = new WebSocket(url);
125         this.websocket.onopen = function(event) {
126             window.setInterval(function() { server.send(['PING']) }, 30000);
127             tui.log_msg("@ server connected!");
128             tui.init_login();
129         };
130     },
131     send: function(tokens) {
132         if (this.websocket.readyState !== WebSocket.OPEN) {
133             tui.log_msg('server disconnected :(');
134         } else {
135             this.websocket.send(unparser.untokenize(tokens));
136         }
137     }
138 }
139
140 let unparser = {
141     quote: function(str) {
142         let quoted = ['"'];
143         for (let i = 0; i < str.length; i++) {
144             let c = str[i];
145             if (c in ['"', '\\']) {
146                 quoted.push('\\');
147             };
148             quoted.push(c);
149         }
150         quoted.push('"');
151         return quoted.join('');
152     },
153     to_yx: function(yx_coordinate) {
154         return "Y:" + yx_coordinate[0] + ",X:" + yx_coordinate[1];
155     },
156     untokenize: function(tokens) {
157         let quoted_tokens = [];
158         for (let token of tokens) {
159             quoted_tokens.push(this.quote(token));
160         }
161         return quoted_tokens.join(" ");
162     }
163 }
164
165 class Mode {
166     constructor(name, has_input_prompt=false, shows_annotations=false, is_intro=false) {
167         this.name = name;
168         this.has_input_prompt = has_input_prompt;
169         this.shows_annotations = shows_annotations;
170         this.is_intro = is_intro;
171     }
172 }
173 let mode_waiting_for_server = new Mode('waiting_for_server', false, false, true);
174 let mode_login = new Mode('login', true, false, true);
175 let mode_chat = new Mode('chat', true, false);
176 let mode_annotate = new Mode('annotate', true, true);
177 let mode_play = new Mode('play', false, false);
178 let mode_study = new Mode('study', false, true);
179 let mode_edit = new Mode('edit', false, false);
180
181 let tui = {
182   mode: mode_waiting_for_server,
183   log: [],
184   input_prompt: '> ',
185   input: '',
186   input_lines: [],
187   window_width: terminal.cols / 2,
188   height_turn_line: 1,
189   height_mode_line: 1,
190   height_input: 1,
191   init: function() {
192       this.recalc_input_lines();
193       this.height_header = this.height_turn_line + this.height_mode_line;
194       this.log_msg("@ waiting for server connection ...");
195   },
196   init_login: function() {
197       this.log_msg("@ please enter your username:");
198       this.switch_mode(mode_login);
199   },
200   switch_mode: function(mode, keep_pos=false) {
201     if (mode == mode_study && !keep_pos) {
202       explorer.position = game.things[game.player_id];
203     }
204     this.mode = mode;
205     this.empty_input();
206     if (mode == mode_annotate && explorer.position in explorer.info_db) {
207         let info = explorer.info_db[explorer.position];
208         if (info != "(none)") {
209             this.add_to_input(explorer.info_db[explorer.position]);
210         }
211     }
212     this.full_refresh();
213   },
214   empty_input: function(str) {
215       this.input = "";
216       if (this.mode.has_input_prompt) {
217           this.recalc_input_lines();
218       } else {
219           this.height_input = 0;
220       }
221   },
222   add_to_input: function(str) {
223       if (this.input_prompt.length + this.input.length + str.length > this.window_width * terminal.rows) {
224           return;
225       }
226       this.input += str;
227       this.recalc_input_lines();
228       this.full_refresh();
229   },
230   recalc_input_lines: function() {
231       this.input_lines = this.msg_into_lines_of_width(this.input_prompt + this.input, this.window_width);
232       this.height_input = this.input_lines.length;
233   },
234   shorten_input: function() {
235       if (this.input.length == 0) {
236           terminal.blink_screen();
237       } else {
238           this.input = tui.input.slice(0, -1);
239           this.recalc_input_lines();
240           this.full_refresh();
241       }
242   },
243   msg_into_lines_of_width: function(msg, width) {
244     let chunk = "";
245     let lines = [];
246     for (let i = 0, x = 0; i < msg.length; i++, x++) {
247       if (x >= width) {
248         lines.push(chunk);
249         chunk = "";
250         x = 0;
251       };
252       chunk += msg[i];
253     }
254     lines.push(chunk);
255     return lines;
256   },
257   log_msg: function(msg) {
258       let lines = this.msg_into_lines_of_width(msg, this.window_width);
259       this.log = this.log.concat(lines);
260       while (this.log.length > terminal.rows) {
261         this.log.shift();
262       };
263       this.full_refresh();
264   },
265   log_help: function() {
266     this.log_msg("");
267     this.log_msg("HELP");
268     this.log_msg("");
269     this.log_msg("chat mode commands:");
270     this.log_msg(":nick NAME - re-name yourself to NAME");
271     this.log_msg(":msg USER TEXT - send TEXT to USER");
272     this.log_msg(":help - show this help");
273     this.log_msg(":play or :p - switch to play mode");
274     this.log_msg(":study or :s - switch to study mode");
275     this.log_msg("");
276     this.log_msg("play mode commands:");
277     this.log_msg("w, a, s, d - move avatar");
278     this.log_msg("f - flatten surroundings");
279     this.log_msg("e - write following ASCII character");
280     this.log_msg("c - switch to chat mode");
281     this.log_msg("? - switch to study mode");
282     this.log_msg("");
283     this.log_msg("study mode commands:");
284     this.log_msg("w, a, s, d - move question mark");
285     this.log_msg("A - annotate terrain");
286     this.log_msg("c - switch to chat mode");
287     this.log_msg("p - switch to play mode");
288     this.log_msg("");
289   },
290   draw_map: function() {
291     let map_lines = [];
292     let line = [];
293     for (let i = 0, j = 0; i < game.map.length; i++, j++) {
294         if (j == game.map_size[1]) {
295             map_lines.push(line);
296             line = [];
297             j = 0;
298         };
299         line.push(game.map[i]);
300     };
301     map_lines.push(line);
302     let player_position = [0,0];
303     let center_pos = [Math.floor(game.map_size[0] / 2),
304                       Math.floor(game.map_size[1] / 2)];
305     for (const thing_id in game.things) {
306         let t = game.things[thing_id];
307         map_lines[t[0]][t[1]] = '@';
308         if (game.player_id == thing_id) {
309             center_pos = t;
310         }
311     };
312     if (tui.mode.shows_annotations) {
313         map_lines[explorer.position[0]][explorer.position[1]] = '?';
314         center_pos = explorer.position;
315     }
316     let offset = [(terminal.rows / 2) - center_pos[0],
317                   this.window_width / 2 - center_pos[1]];
318       for (let term_y = offset[0], map_y = 0;
319            term_y < terminal.rows && map_y < game.map_size[0];
320            term_y++, map_y++) {
321         if (term_y >= 0) {
322             let to_draw = map_lines[map_y].join('').slice(0, this.window_width - offset[1]);
323             terminal.write(term_y, offset[1], to_draw);
324         }
325     }
326   },
327   draw_mode_line: function() {
328       terminal.write(0, this.window_width, 'MODE: ' + this.mode.name);
329   },
330   draw_turn_line: function(n) {
331     terminal.write(1, this.window_width, 'TURN: ' + game.turn);
332   },
333   draw_history: function() {
334     if (terminal.rows <= this.height_header + this.height_input) {
335         return;
336     }
337       for (let y = terminal.rows - 1 - this.height_input,
338                i = this.log.length - 1;
339            y >= this.height_header && i >= 0;
340            y--, i--) {
341           terminal.write(y, this.window_width, this.log[i]);
342       }
343   },
344   draw_info: function() {
345     let lines = this.msg_into_lines_of_width(explorer.get_info(), this.window_width);
346     for (let y = this.height_header, i = 0; y < terminal.rows && i < lines.length; y++, i++) {
347       terminal.write(y, this.window_width, lines[i]);
348     }
349   },
350   draw_input: function() {
351     if (this.mode.has_input_prompt) {
352         for (let y = terminal.rows - this.height_input, i = 0; y < terminal.rows && i < this.input_lines.length; y++, i++) {
353             terminal.write(y, this.window_width, this.input_lines[i]);
354         }
355     }
356   },
357   full_refresh: function() {
358     terminal.drawBox(0, 0, terminal.rows, terminal.cols);
359     if (this.mode.is_intro) {
360         this.draw_history();
361         this.draw_input();
362     } else {
363         this.draw_map();
364         this.draw_turn_line();
365         this.draw_mode_line();
366         if (this.mode.shows_annotations) {
367           this.draw_info();
368         } else {
369           this.draw_history();
370         }
371         this.draw_input();
372     }
373     terminal.refresh();
374   }
375 }
376
377 let game = {
378   things: {},
379   turn: 0,
380   map: "",
381   map_size: [0,0],
382   player_id: 0
383 }
384
385 terminal.initialize();
386 tui.init();
387 tui.full_refresh();
388
389 server.init(websocket_location);
390 server.websocket.onmessage = function (event) {
391   let tokens = parser.tokenize(event.data)[0];
392   if (tokens[0] === 'TURN') {
393     game.things = {}
394     game.turn = parseInt(tokens[1]);
395   } else if (tokens[0] === 'THING_POS') {
396     game.things[tokens[1]] = parser.parse_yx(tokens[2]);
397   } else if (tokens[0] === 'MAP') {
398     game.map_size = parser.parse_yx(tokens[1]);
399     game.map = tokens[2]
400   } else if (tokens[0] === 'GAME_STATE_COMPLETE') {
401     explorer.empty_info_db();
402     if (tui.mode == mode_study) {
403       explorer.query_info();
404     }
405     tui.full_refresh();
406   } else if (tokens[0] === 'CHAT') {
407      tui.log_msg('# ' + tokens[1], 1);
408   } else if (tokens[0] === 'PLAYER_ID') {
409       game.player_id = parseInt(tokens[1]);
410   } else if (tokens[0] === 'META') {
411      tui.log_msg('@ ' + tokens[1]);
412   } else if (tokens[0] === 'LOGIN_OK') {
413       server.send(['GET_GAMESTATE']);
414       tui.log_help();
415       tui.log_msg('@ ' + tokens[1]);
416       tui.switch_mode(mode_chat);
417   } else if (tokens[0] === 'ANNOTATION') {
418      let position = parser.parse_yx(tokens[1]);
419      explorer.update_info_db(position, tokens[2]);
420   } else if (tokens[0] === 'UNHANDLED_INPUT') {
421      tui.log_msg('? unknown command');
422   } else if (tokens[0] === 'PLAY_ERROR') {
423      terminal.blink_screen();
424   } else if (tokens[0] === 'ARGUMENT_ERROR') {
425      tui.log_msg('? syntax error: ' + tokens[1]);
426   } else if (tokens[0] === 'GAME_ERROR') {
427      tui.log_msg('? game error: ' + tokens[1]);
428   } else if (tokens[0] === 'PONG') {
429     console.log('PONG');
430   } else {
431      tui.log_msg('? unhandled input: ' + event.data);
432   }
433 }
434
435 let explorer = {
436     position: [0,0],
437     info_db: {},
438     move: function(direction) {
439         let try_pos = [0,0];
440         try_pos[0] = this.position[0];
441         try_pos[1] = this.position[1];
442         if (direction == 'left') {
443             try_pos[1] -= 1;
444         } else if (direction == 'right') {
445             try_pos[1] += 1;
446         } else if (direction == 'up') {
447             try_pos[0] -= 1;
448         } else if (direction == 'down') {
449             try_pos[0] += 1;
450         };
451         if (!(try_pos[0] < 0) &&
452             !(try_pos[1] < 0) &&
453             !(try_pos[0] >= game.map_size[0])
454             && !(try_pos[1] >= game.map_size[1])) {
455             this.position = try_pos;
456             this.query_info();
457             tui.full_refresh();
458         }
459     },
460     update_info_db: function(yx, str) {
461         this.info_db[yx] = str;
462         if (tui.mode == mode_study) {
463             tui.full_refresh();
464         }
465     },
466     empty_info_db: function() {
467         this.info_db = {};
468         if (tui.mode == mode_study) {
469             tui.full_refresh();
470         }
471     },
472     query_info: function() {
473         server.send(["GET_ANNOTATION", unparser.to_yx(explorer.position)]);
474     },
475     get_info: function() {
476         if (this.position in this.info_db) {
477             return this.info_db[this.position];
478         } else {
479             return 'waiting …';
480         }
481     },
482     annotate: function(msg) {
483         if (msg.length == 0) {
484             msg = " ";  // triggers annotation deletion
485         }
486         server.send(["ANNOTATE", unparser.to_yx(explorer.position), msg]);
487     }
488 }
489
490 document.addEventListener('keydown', (event) => {
491     if (tui.mode.has_input_prompt && event.key.length === 1) {
492         tui.add_to_input(event.key);
493     } else if (tui.mode.has_input_prompt && event.key == 'Backspace') {
494         tui.shorten_input();
495     } else if (tui.mode == mode_login && event.key == 'Enter') {
496         server.send(['LOGIN', tui.input]);
497         tui.switch_mode(mode_login);
498     } else if (tui.mode == mode_annotate && event.key == 'Enter') {
499         explorer.annotate(tui.input);
500         tui.switch_mode(mode_study, true);
501     } else if (tui.mode == mode_chat && event.key == 'Enter') {
502         let [tokens, token_starts] = parser.tokenize(tui.input);
503         if (tokens.length > 0 && tokens[0].length > 0) {
504             if (tokens[0][0] == ':') {
505                 if (tokens[0] == ':play' || tokens[0] == ':p') {
506                     tui.switch_mode(mode_play);
507                 } else if (tokens[0] == ':study' || tokens[0] == ':s') {
508                     tui.switch_mode(mode_study);
509                 } else if (tokens[0] == ':help') {
510                     tui.log_help();
511                 } else if (tokens[0] == ':nick') {
512                     if (tokens.length > 1) {
513                         server.send(['LOGIN', tokens[1]]);
514                     } else {
515                         tui.log_msg('? need login name');
516                     }
517                 } else if (tokens[0] == ':msg') {
518                     if (tokens.length > 2) {
519                         let msg = tui.input.slice(token_starts[2]);
520                         server.send(['QUERY', tokens[1], msg]);
521                     } else {
522                         tui.log_msg('? need message target and message');
523                     }
524                 } else {
525                     tui.log_msg('? unknown command');
526                 }
527             } else {
528                 server.send(['ALL', tui.input]);
529             }
530         }
531         tui.empty_input();
532         tui.full_refresh();
533       } else if (tui.mode == mode_play) {
534           if (event.key === 'c') {
535               tui.switch_mode(mode_chat);
536           } else if (event.key === 'e') {
537               tui.switch_mode(mode_edit);
538           } else if (event.key === '?') {
539               tui.switch_mode(mode_study);
540           } else if (event.key === 'F1') {
541               tui.log_help();
542           } else if (event.key === 'f') {
543               server.send(["TASK:FLATTEN_SURROUNDINGS"]);
544           } else if (event.key === 'a') {
545               server.send(['TASK:MOVE', 'LEFT']);
546           } else if (event.key === 'd') {
547               server.send(['TASK:MOVE', 'RIGHT']);
548           } else if (event.key === 'w') {
549               server.send(['TASK:MOVE', 'UP']);
550           } else if (event.key === 's') {
551               server.send(['TASK:MOVE', 'DOWN']);
552           };
553     } else if (tui.mode == mode_edit) {
554         if (event.key != "Shift" && event.key.length == 1) {
555             server.send(["TASK:WRITE", event.key]);
556             tui.switch_mode(mode_play);
557         }
558     } else if (tui.mode == mode_study) {
559         if (event.key === 'c') {
560             tui.switch_mode(mode_chat);
561         } else if (event.key == 'p') {
562             tui.switch_mode(mode_play);
563         } else if (event.key === 'a') {
564               explorer.move('left');
565         } else if (event.key === 'd') {
566               explorer.move('right');
567         } else if (event.key === 'w') {
568               explorer.move('up');
569         } else if (event.key === 's') {
570               explorer.move('down');
571         } else if (event.key === 'A') {
572           tui.switch_mode(mode_annotate);
573         };
574     }
575 }, false);
576 </script>
577 </body></html>