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