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