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