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