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