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