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