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