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