home · contact · privacy
Improved input prompt handling.
[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             server.send(['GET_GAMESTATE']);
128         };
129     },
130     send: function(tokens) {
131         this.websocket.send(unparser.untokenize(tokens));
132     }
133 }
134
135 let unparser = {
136     quote: function(str) {
137         let quoted = ['"'];
138         for (let i = 0; i < str.length; i++) {
139             let c = str[i];
140             if (c in ['"', '\\']) {
141                 quoted.push('\\');
142             };
143             quoted.push(c);
144         }
145         quoted.push('"');
146         return quoted.join('');
147     },
148     to_yx: function(yx_coordinate) {
149         return "Y:" + yx_coordinate[0] + ",X:" + yx_coordinate[1];
150     },
151     untokenize: function(tokens) {
152         let quoted_tokens = [];
153         for (let token of tokens) {
154             quoted_tokens.push(this.quote(token));
155         }
156         return quoted_tokens.join(" ");
157     }
158 }
159
160 class Mode {
161     constructor(name, has_input_prompt=false, shows_annotations=false) {
162         this.name = name;
163         this.has_input_prompt = has_input_prompt;
164         this.shows_annotations = shows_annotations;
165     }
166 }
167 let mode_chat = new Mode('chat', true, false);
168 let mode_annotate = new Mode('annotate', true, true);
169 let mode_play = new Mode('play', false, false);
170 let mode_study = new Mode('study', false, true);
171 let mode_edit = new Mode('edit', false, false);
172
173 let tui = {
174   mode: mode_chat,
175   log: [],
176   input_prompt: '> ',
177   input: '',
178   input_lines: [],
179   window_width: terminal.cols / 2,
180   height_turn_line: 1,
181   height_mode_line: 1,
182   height_input: 1,
183   init: function() {
184       this.recalc_input_lines();
185       this.height_header = this.height_turn_line + this.height_mode_line;
186   },
187   switch_mode: function(mode, keep_pos=false) {
188     if (mode == mode_study && !keep_pos) {
189       explorer.position = game.things[game.player_id];
190     }
191     this.mode = mode;
192     this.empty_input();
193     this.full_refresh();
194   },
195   draw_mode_line: function() {
196       terminal.drawBox(1, this.window_width, this.height_mode_line, this.window_width);
197       terminal.write(1, this.window_width, 'MODE ' + this.mode.name);
198   },
199   draw_history: function() {
200     if (terminal.rows <= this.height_header + this.height_input) {
201         return;
202     }
203     terminal.drawBox(this.height_header, this.window_width, terminal.rows - this.height_header - this.height_input, this.window_width);
204       for (let y = terminal.rows - 1 - this.height_input,
205                i = this.log.length - 1;
206            y >= this.height_header && i >= 0;
207            y--, i--) {
208           terminal.write(y, this.window_width, this.log[i]);
209       }
210   },
211   draw_map: function() {
212     terminal.drawBox(0, 0, terminal.rows, this.window_width);
213     let map_lines = [];
214     let line = [];
215     for (let i = 0, j = 0; i < game.map.length; i++, j++) {
216         if (j == game.map_size[1]) {
217             map_lines.push(line);
218             line = [];
219             j = 0;
220         };
221         line.push(game.map[i]);
222     };
223     map_lines.push(line);
224     let player_position = [0,0];
225     let center_pos = [Math.floor(game.map_size[0] / 2),
226                       Math.floor(game.map_size[1] / 2)];
227     for (const thing_id in game.things) {
228         let t = game.things[thing_id];
229         map_lines[t[0]][t[1]] = '@';
230         if (game.player_id == thing_id) {
231             center_pos = t;
232         }
233     };
234     if (tui.mode.shows_annotations) {
235         map_lines[explorer.position[0]][explorer.position[1]] = '?';
236         center_pos = explorer.position;
237     }
238     let offset = [(terminal.rows / 2) - center_pos[0],
239                   this.window_width / 2 - center_pos[1]];
240       for (let term_y = offset[0], map_y = 0;
241            term_y < terminal.rows && map_y < game.map_size[0];
242            term_y++, map_y++) {
243         if (term_y >= 0) {
244             let to_draw = map_lines[map_y].join('').slice(0, this.window_width - offset[1]);
245             terminal.write(term_y, offset[1], to_draw);
246         }
247     }
248   },
249   draw_turn_line: function(n) {
250     terminal.drawBox(0, this.window_width, 1, this.window_width);
251     terminal.write(0, this.window_width, 'turn: ' + game.turn);
252   },
253   empty_input: function(str) {
254       this.input = "";
255       if (this.mode.has_input_prompt) {
256           this.recalc_input_lines();
257       } else {
258           this.height_input = 0;
259       }
260   },
261   add_to_input: function(str) {
262       if (this.input_prompt.length + this.input.length + str.length > this.window_width * terminal.rows) {
263           return;
264       }
265       this.input += str;
266       this.recalc_input_lines();
267   },
268   recalc_input_lines: function() {
269       this.input_lines = this.msg_into_lines_of_width(this.input_prompt + this.input, this.window_width);
270       this.height_input = this.input_lines.length;
271   },
272   shorten_input: function() {
273       if (this.input.length == 0) {
274           terminal.blink_screen();
275       } else {
276           this.input = tui.input.slice(0, -1);
277           this.recalc_input_lines();
278       }
279   },
280   draw_input: function() {
281     terminal.drawBox(terminal.rows - this.height_input, this.window_width, this.height_input, this.window_width);
282     if (this.mode.has_input_prompt) {
283         for (let y = terminal.rows - this.height_input, i = 0; y < terminal.rows && i < this.input_lines.length; y++, i++) {
284             terminal.write(y, this.window_width, this.input_lines[i]);
285         }
286     }
287   },
288   msg_into_lines_of_width: function(msg, width) {
289     let chunk = "";
290     let lines = [];
291     for (let i = 0, x = 0; i < msg.length; i++, x++) {
292       if (x >= width) {
293         lines.push(chunk);
294         chunk = "";
295         x = 0;
296       };
297       chunk += msg[i];
298     }
299     lines.push(chunk);
300     return lines;
301   },
302   log_msg: function(msg) {
303       let lines = this.msg_into_lines_of_width(msg, this.window_width);
304       this.log = this.log.concat(lines);
305       while (this.log.length > terminal.rows) {
306         this.log.shift();
307       };
308       this.draw_history();
309   },
310   refresh: function() {
311     terminal.refresh();
312   },
313   log_help: function() {
314     tui.log_msg("");
315     tui.log_msg("HELP");
316     tui.log_msg("");
317     tui.log_msg("chat mode commands:");
318     tui.log_msg(":login USER - register as USER");
319     tui.log_msg(":msg USER TEXT - send TEXT to USER");
320     tui.log_msg(":help - show this help");
321     tui.log_msg(":play or :p - switch to play mode");
322     tui.log_msg(":study or :s - switch to study mode");
323     tui.log_msg("");
324     tui.log_msg("play mode commands:");
325     tui.log_msg("w, a, s, d - move avatar");
326     tui.log_msg("f - flatten surroundings");
327     tui.log_msg("e - write following ASCII character");
328     tui.log_msg("c - switch to chat mode");
329     tui.log_msg("? - switch to study mode");
330     tui.log_msg("");
331     tui.log_msg("study mode commands:");
332     tui.log_msg("w, a, s, d - move question mark");
333     tui.log_msg("A - annotate terrain");
334     tui.log_msg("c - switch to chat mode");
335     tui.log_msg("p - switch to play mode");
336     tui.log_msg("");
337   },
338   draw_info: function() {
339     terminal.drawBox(this.height_header, this.window_width, terminal.rows - this.height_header - this.height_input, this.window_width);
340     let lines = this.msg_into_lines_of_width(explorer.get_info(), this.window_width);
341     for (let y = this.height_header, i = 0; y < terminal.rows && i < lines.length; y++, i++) {
342       terminal.write(y, this.window_width, lines[i]);
343     }
344   },
345   full_refresh: function() {
346     this.draw_map();
347     this.draw_turn_line();
348     this.draw_mode_line();
349     if (this.mode.shows_annotations) {
350       this.draw_info();
351     } else {
352       this.draw_history();
353     }
354     this.draw_input();
355     this.refresh();
356   }
357 }
358
359 let game = {
360   things: {},
361   turn: 0,
362   map: "",
363   map_size: [0,0],
364   player_id: 0
365 }
366
367 terminal.initialize();
368 tui.init();
369 tui.log_help();
370 tui.full_refresh();
371
372 server.init(websocket_location);
373 server.websocket.onmessage = function (event) {
374   let tokens = parser.tokenize(event.data)[0];
375   if (tokens[0] === 'TURN') {
376     game.things = {}
377     game.turn = parseInt(tokens[1]);
378   } else if (tokens[0] === 'THING_POS') {
379     game.things[tokens[1]] = parser.parse_yx(tokens[2]);
380   } else if (tokens[0] === 'MAP') {
381     game.map_size = parser.parse_yx(tokens[1]);
382     game.map = tokens[2]
383   } else if (tokens[0] === 'GAME_STATE_COMPLETE') {
384     explorer.empty_info_db();
385     if (tui.mode == mode_study) {
386       explorer.query_info();
387     }
388     tui.draw_turn_line();
389     tui.draw_map();
390     tui.refresh();
391   } else if (tokens[0] === 'CHAT') {
392      tui.log_msg('# ' + tokens[1], 1);
393      tui.refresh();
394   } else if (tokens[0] === 'PLAYER_ID') {
395       game.player_id = parseInt(tokens[1]);
396   } else if (tokens[0] === 'META') {
397      tui.log_msg('@ ' + tokens[1]);
398      tui.refresh();
399   } else if (tokens[0] === 'ANNOTATION') {
400      let position = parser.parse_yx(tokens[1]);
401      explorer.update_info_db(position, tokens[2]);
402   } else if (tokens[0] === 'UNHANDLED_INPUT') {
403      tui.log_msg('? unknown command');
404      tui.refresh();
405   } else if (tokens[0] === 'PLAY_ERROR') {
406      terminal.blink_screen();
407   } else if (tokens[0] === 'ARGUMENT_ERROR') {
408      tui.log_msg('? syntax error: ' + tokens[1]);
409      tui.refresh();
410   } else if (tokens[0] === 'GAME_ERROR') {
411      tui.log_msg('? game error: ' + tokens[1]);
412      tui.refresh();
413   } else if (tokens[0] === 'PONG') {
414     console.log('PONG');
415   } else {
416      tui.log_msg('? unhandled input: ' + event.data);
417      tui.refresh();
418   }
419 }
420
421 let explorer = {
422     position: [0,0],
423     info_db: {},
424     move: function(direction) {
425         let try_pos = [0,0];
426         try_pos[0] = this.position[0];
427         try_pos[1] = this.position[1];
428         if (direction == 'left') {
429             try_pos[1] -= 1;
430         } else if (direction == 'right') {
431             try_pos[1] += 1;
432         } else if (direction == 'up') {
433             try_pos[0] -= 1;
434         } else if (direction == 'down') {
435             try_pos[0] += 1;
436         };
437         if (!(try_pos[0] < 0) &&
438             !(try_pos[1] < 0) &&
439             !(try_pos[0] >= game.map_size[0])
440             && !(try_pos[1] >= game.map_size[1])) {
441             this.position = try_pos;
442             this.query_info();
443             tui.draw_map();
444             tui.draw_info();
445             tui.refresh();
446         }
447     },
448     update_info_db: function(yx, str) {
449         this.info_db[yx] = str;
450         if (tui.mode == mode_study) {
451             tui.draw_info();
452             tui.refresh();
453         }
454     },
455     empty_info_db: function() {
456         this.info_db = {};
457         if (tui.mode == mode_study) {
458             tui.draw_info();
459             tui.refresh();
460         }
461     },
462     query_info: function() {
463         server.send(["GET_ANNOTATION", unparser.to_yx(explorer.position)]);
464     },
465     get_info: function() {
466         if (this.position in this.info_db) {
467             return this.info_db[this.position];
468         } else {
469             return 'waiting …';
470         }
471     },
472     annotate: function(msg) {
473         if (msg.length == 0) {
474             msg = " ";  // triggers annotation deletion
475         }
476         server.send(["ANNOTATE", unparser.to_yx(explorer.position), msg]);
477     }
478 }
479
480 document.addEventListener('keydown', (event) => {
481     if (tui.mode.has_input_prompt && event.key.length === 1) {
482         tui.add_to_input(event.key);
483         tui.full_refresh();
484     } else if (tui.mode.has_input_prompt && event.key == 'Backspace') {
485         tui.shorten_input();
486         tui.full_refresh();
487     } else if (tui.mode == mode_annotate && event.key == 'Enter') {
488         explorer.annotate(tui.input);
489         tui.switch_mode(mode_study, true);
490     } else if (tui.mode == mode_chat && event.key == 'Enter') {
491         let [tokens, token_starts] = parser.tokenize(tui.input);
492         if (tokens.length > 0 && tokens[0].length > 0) {
493             if (tokens[0][0] == ':') {
494                 if (tokens[0] == ':play' || tokens[0] == ':p') {
495                     tui.switch_mode(mode_play);
496                 } else if (tokens[0] == ':study' || tokens[0] == ':s') {
497                     tui.switch_mode(mode_study);
498                 } else if (tokens[0] == ':help') {
499                     tui.log_help();
500                     tui.refresh();
501                 } else if (tokens[0] == ':login') {
502                     if (tokens.length > 1) {
503                         server.send(['LOGIN', tokens[1]]);
504                     } else {
505                         tui.log_msg('? need login name');
506                     }
507                 } else if (tokens[0] == ':msg') {
508                     if (tokens.length > 2) {
509                         let msg = tui.input.slice(token_starts[2]);
510                         server.send(['QUERY', tokens[1], msg]);
511                     } else {
512                         tui.log_msg('? need message target and message');
513                     }
514                 } else {
515                     tui.log_msg('? unknown command');
516                 }
517             } else {
518                 server.send(['ALL', tui.input]);
519             }
520         }
521         tui.empty_input();
522         tui.full_refresh();
523       } else if (tui.mode == mode_play) {
524           if (event.key === 'c') {
525               tui.switch_mode(mode_chat);
526           } else if (event.key === 'e') {
527               tui.switch_mode(mode_edit);
528           } else if (event.key === '?') {
529               tui.switch_mode(mode_study);
530           } else if (event.key === 'F1') {
531               tui.log_help();
532               tui.refresh();
533           } else if (event.key === 'f') {
534               server.send(["TASK:FLATTEN_SURROUNDINGS"]);
535           } else if (event.key === 'a') {
536               server.send(['TASK:MOVE', 'LEFT']);
537           } else if (event.key === 'd') {
538               server.send(['TASK:MOVE', 'RIGHT']);
539           } else if (event.key === 'w') {
540               server.send(['TASK:MOVE', 'UP']);
541           } else if (event.key === 's') {
542               server.send(['TASK:MOVE', 'DOWN']);
543           };
544     } else if (tui.mode == mode_edit) {
545         if (event.key != "Shift" && event.key.length == 1) {
546             server.send(["TASK:WRITE", event.key]);
547             tui.switch_mode(mode_play);
548         }
549     } else if (tui.mode == mode_study) {
550         if (event.key === 'c') {
551             tui.switch_mode(mode_chat);
552         } else if (event.key == 'p') {
553             tui.switch_mode(mode_play);
554         } else if (event.key === 'a') {
555               explorer.move('left');
556         } else if (event.key === 'd') {
557               explorer.move('right');
558         } else if (event.key === 'w') {
559               explorer.move('up');
560         } else if (event.key === 's') {
561               explorer.move('down');
562         } else if (event.key === 'A') {
563           tui.switch_mode(mode_annotate);
564           tui.draw_info();
565           tui.refresh();
566         };
567     }
568 }, false);
569 </script>
570 </body></html>