home · contact · privacy
In web client, keep scrolling position even on focus change.
[plomrogue2] / rogue_chat.html
1 <!DOCTYPE html>
2 <html><head>
3 <style>
4   pre {
5       display: inline-block;
6   }
7   pre a {
8       color: white;
9   }
10 </style>
11 </head><body>
12 <div>
13 terminal rows: <input id="n_rows" type="number" step=4 min=24 value=24 />
14 / terminal columns: <input id="n_cols" type="number" step=4 min=80 value=80 />
15 / <a href="https://plomlompom.com/repos/?p=plomrogue2;a=summary">source code</a> (includes proper terminal/ncurses client)
16 </div>
17 <pre id="terminal"></pre>
18 <textarea id="input" style="opacity: 0; width: 0px;"></textarea>
19 <h3>button controls for hard-to-remember keybindings</h3>
20 <table id="move_table" style="float: left">
21   <tr>
22     <td style="text-align: right"><button id="hex_move_upleft"></button></td>
23     <td style="text-align: center"><button id="square_move_up"></button></td>
24     <td><button id="hex_move_upright"></button></td>
25   </tr>
26   <tr>
27     <td style="text-align: right;"><button id="square_move_left"></button><button id="hex_move_left">left</button></td>
28     <td stlye="text-align: center;">move</td>
29     <td><button id="square_move_right"></button><button id="hex_move_right"></button></td>
30   </tr>
31   <tr>
32     <td><button id="hex_move_downleft"></button></td>
33     <td style="text-align: center"><button id="square_move_down"></button></td>
34     <td><button id="hex_move_downright"></button></td>
35   </tr>
36 </table>
37 <table>
38   <tr>
39     <td><button id="help"></button></td>
40   </tr>
41   <tr>
42     <td><button id="switch_to_chat"></button><br /></td>
43   </tr>
44   <tr>
45     <td><button id="switch_to_study"></button></td>
46     <td><button id="toggle_map_mode"></button>
47   </tr>
48   <tr>
49     <td><button id="switch_to_play"></button></td>
50     <td>
51       <button id="switch_to_take_thing"></button>
52       <button id="switch_to_drop_thing"></button>
53       <button id="door"></button>
54       <button id="consume"></button>
55       <button id="switch_to_command_thing"></button>
56       <button id="teleport"></button>
57       <button id="wear"></button>
58       <button id="spin"></button>
59     </td>
60   </tr>
61   <tr>
62     <td><button id="switch_to_edit"></button></td>
63     <td>
64       <button id="switch_to_write"></button>
65       <button id="flatten"></button>
66       <button id="install"></button>
67       <button id="switch_to_annotate"></button>
68       <button id="switch_to_portal"></button>
69       <button id="switch_to_name_thing"></button>
70       <button id="switch_to_password"></button>
71       <button id="switch_to_enter_face"></button>
72     </td>
73   </tr>
74   <tr>
75     <td><button id="switch_to_admin_enter"></button></td>
76     <td>
77       <button id="switch_to_control_pw_type"></button>
78       <button id="switch_to_control_tile_type"></button>
79       <button id="switch_to_admin_thing_protect"></button>
80       <button id="toggle_tile_draw"></button>
81     </td>
82   <tr>
83   </tr>
84 </table>
85 <h3>edit keybindings</h3> (see <a href="https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values">here</a> for non-obvious available values):<br />
86 <ul>
87 <li>move up (square grid): <input id="key_square_move_up" type="text" value="w" /> (hint: ArrowUp)
88 <li>move left (square grid): <input id="key_square_move_left" type="text" value="a" /> (hint: ArrowLeft)
89 <li>move down (square grid): <input id="key_square_move_down" type="text" value="s" /> (hint: ArrowDown)
90 <li>move right (square grid): <input id="key_square_move_right" type="text" value="d" /> (hint: ArrowRight)
91 <li>move up-left (hex grid): <input id="key_hex_move_upleft" type="text" value="w" />
92 <li>move up-right (hex grid): <input id="key_hex_move_upright" type="text" value="e" />
93 <li>move right (hex grid): <input id="key_hex_move_right" type="text" value="d" />
94 <li>move down-right (hex grid): <input id="key_hex_move_downright" type="text" value="x" />
95 <li>move down-left (hex grid): <input id="key_hex_move_downleft" type="text" value="y" />
96 <li>move left (hex grid): <input id="key_hex_move_left" type="text" value="a" />
97 <li>help: <input id="key_help" type="text" value="h" />
98 <li>flatten surroundings: <input id="key_flatten" type="text" value="F" />
99 <li>teleport: <input id="key_teleport" type="text" value="p" />
100 <li>spin: <input id="key_spin" type="text" value="S" />
101 <li>open/close: <input id="key_door" type="text" value="D" />
102 <li>consume: <input id="key_consume" type="text" value="C" />
103 <li>install: <input id="key_install" type="text" value="I" />
104 <li>(un-)wear: <input id="key_wear" type="text" value="W" />
105 <li><input id="key_switch_to_drop_thing" type="text" value="u" />
106 <li><input id="key_switch_to_enter_face" type="text" value="f" />
107 <li><input id="key_switch_to_take_thing" type="text" value="z" />
108 <li><input id="key_switch_to_chat" type="text" value="t" />
109 <li><input id="key_switch_to_play" type="text" value="p" />
110 <li><input id="key_switch_to_study" type="text" value="?" />
111 <li><input id="key_switch_to_edit" type="text" value="E" />
112 <li><input id="key_switch_to_write" type="text" value="m" />
113 <li><input id="key_switch_to_name_thing" type="text" value="N" />
114 <li><input id="key_switch_to_command_thing" type="text" value="O" />
115 <li><input id="key_switch_to_password" type="text" value="P" />
116 <li><input id="key_switch_to_admin_enter" type="text" value="A" />
117 <li><input id="key_switch_to_control_pw_type" type="text" value="C" />
118 <li><input id="key_switch_to_control_tile_type" type="text" value="Q" />
119 <li><input id="key_switch_to_admin_thing_protect" type="text" value="T" />
120 <li><input id="key_switch_to_annotate" type="text" value="M" />
121 <li><input id="key_switch_to_portal" type="text" value="T" />
122 <li>toggle map view: <input id="key_toggle_map_mode" type="text" value="L" />
123 <li>toggle protection character drawing: <input id="key_toggle_tile_draw" type="text" value="m" />
124 </ul>
125 </div>
126 <script>
127 "use strict";
128 let websocket_location = "wss://plomlompom.com/rogue_chat/";
129 //let websocket_location = "ws://localhost:8000/";
130
131 let mode_helps = {
132     'play': {
133         'short': 'play',
134         'intro': '',
135         'long': 'This mode allows you to interact with the map in various ways.'
136     },
137     'study': {
138         'short': 'study',
139         'intro': '',
140         'long': 'This mode allows you to study the map and its tiles in detail.  Move the question mark over a tile, and the right half of the screen will show detailed information on it.  Toggle the map view to show or hide different information layers.'},
141     'edit': {
142         'short': 'world edit',
143         'intro': '',
144         'long': 'This mode allows you to change the game world in various ways.  Individual map tiles can be protected by "protection characters", which you can see by toggling into the protections map view.  You can edit a tile if you set the world edit password that matches its protection character.  The character "." marks the absence of protection:  Such tiles can always be edited.'
145     },
146     'name_thing': {
147         'short': 'name thing',
148         'intro': '',
149         'long': 'Give name to/change name of thing here.'
150     },
151     'command_thing': {
152         'short': 'command thing',
153         'intro': '',
154         'long': 'Enter a command to the thing you carry.  Enter nothing to return to play mode.'
155     },
156     'take_thing': {
157         'short': 'take thing',
158         'intro': 'Pick up a thing in reach by entering its index number.  Enter nothing to abort.',
159         'long': 'You see a list of things which you could pick up.  Enter the target thing\'s index, or, to leave, nothing.'
160     },
161     'drop_thing': {
162         'short': 'drop thing',
163         'intro': 'Enter number of direction to which you want to drop thing.',
164         'long': 'Drop currently carried thing by entering the target direction index.  Enter nothing to return to play mode..'
165     },
166     'admin_thing_protect': {
167         'short': 'change thing protection',
168         'intro': '@ enter thing protection character:',
169         'long': 'Change protection character for thing here.'
170     },
171     'enter_face': {
172         'short': 'enter your face',
173         'intro': '@ enter face line (enter nothing to abort):',
174         'long': 'Draw your face as ASCII art.  The string you enter must be 18 characters long, and will be divided on display into 3 lines of 6 characters each, from top to bottom..'
175     },
176     'write': {
177         'short': 'change terrain',
178         'intro': '',
179         'long': 'This mode allows you to change the map tile you currently stand on (if your world editing password authorizes you so).  Just enter any printable ASCII character to imprint it on the ground below you.'
180     },
181     'control_pw_type': {
182         'short': 'change protection character password',
183         'intro': '@ enter protection character for which you want to change the password:',
184         'long': 'This mode is the first of two steps to change the password for a protection character.  First enter the protection character for which you want to change the password.'
185     },
186     'control_pw_pw': {
187         'short': 'change protection character password',
188         'intro': '',
189         'long': 'This mode is the second of two steps to change the password for a protection character.  Enter the new password for the protection character you chose.'
190     },
191     'control_tile_type': {
192         'short': 'change tiles protection',
193         'intro': '@ enter protection character which you want to draw:',
194         'long': 'This mode is the first of two steps to change tile protection areas on the map.  First enter the tile protection character you want to write.'
195     },
196     'control_tile_draw': {
197         'short': 'change tiles protection',
198         'intro': '',
199         'long': 'This mode is the second of two steps to change tile protection areas on the map.  Toggle tile protection drawing on/off and move the ?? cursor around the map to draw the selected protection character.'
200     },
201     'annotate': {
202         'short': 'annotate tile',
203         'intro': '',
204         'long': 'This mode allows you to add/edit a comment on the tile you are currently standing on (provided your world editing password authorizes you so).  Hit Return to leave.'
205     },
206     'portal': {
207         'short': 'edit portal',
208         'intro': '',
209         'long': 'This mode allows you to imprint/edit/remove a teleportation target on the ground you are currently standing on (provided your world editing password authorizes you so).  Enter or edit a URL to imprint a teleportation target; enter emptiness to remove a pre-existing teleportation target.  Hit Return to leave.'
210     },
211     'chat': {
212         'short': 'chat',
213         'intro': '',
214         'long': 'This mode allows you to engage in chit-chat with other users.  Any line you enter into the input prompt that does not start with a "/" will be sent out to nearby players – but barriers and distance will reduce what they can read, so stand close to them to ensure they get your message.  Lines that start with a "/" are used for commands like:\n\n/nick NAME – re-name yourself to NAME'
215     },
216     'login': {
217         'short': 'login',
218         'intro': '',
219         'long': 'Enter your player name.'
220     },
221     'waiting_for_server': {
222         'short': 'waiting for server response',
223         'intro': '@ waiting for server …',
224         'long': 'Waiting for a server response.'
225     },
226     'post_login_wait': {
227         'short': 'waiting for server response',
228         'intro': '',
229         'long': 'Waiting for a server response.'
230     },
231     'password': {
232         'short': 'set world edit password',
233         'intro': '',
234         'long': 'This mode allows you to change the password that you send to authorize yourself for editing password-protected elements of the world.  Hit return to confirm and leave.'
235     },
236     'admin_enter': {
237         'short': 'become admin',
238         'intro': '@ enter admin password:',
239         'long': 'This mode allows you to become admin if you know an admin password.'
240     },
241     'admin': {
242         'short': 'admin',
243         'intro': '',
244         'long': 'This mode allows you access to actions limited to administrators.'
245     }
246 }
247 let key_descriptions = {
248     'help': 'help',
249     'flatten': 'flatten surroundings',
250     'teleport': 'teleport',
251     'door': 'open/close',
252     'consume': 'consume',
253     'install': '(un-)install',
254     'wear': '(un-)wear',
255     'spin': 'spin',
256     'toggle_map_mode': 'toggle map view',
257     'toggle_tile_draw': 'toggle protection character drawing',
258     'hex_move_upleft': 'up-left',
259     'hex_move_upright': 'up-right',
260     'hex_move_right': 'right',
261     'hex_move_left': 'left',
262     'hex_move_downleft': 'down-left',
263     'hex_move_downright': 'down-right',
264     'square_move_up': 'up',
265     'square_move_left': 'left',
266     'square_move_down': 'down',
267     'square_move_right': 'right',
268 };
269 for (const mode_name of Object.keys(mode_helps)) {
270     key_descriptions['switch_to_' + mode_name] = mode_helps[mode_name].short;
271 };
272
273 let rows_selector = document.getElementById("n_rows");
274 let cols_selector = document.getElementById("n_cols");
275 let key_selectors = document.querySelectorAll('[id^="key_"]');
276
277 for (const key_switch_selector of document.querySelectorAll('[id^="key_switch_to_"]')) {
278     const action = key_switch_selector.id.slice("key_switch_to_".length);
279     key_switch_selector.parentNode.prepend(mode_helps[action].short + ': ');
280 }
281
282 function restore_selector_value(selector) {
283     let stored_selection = window.localStorage.getItem(selector.id);
284     if (stored_selection) {
285         selector.value = stored_selection;
286     }
287 }
288 restore_selector_value(rows_selector);
289 restore_selector_value(cols_selector);
290 for (let key_selector of key_selectors) {
291     restore_selector_value(key_selector);
292 }
293
294 function escapeHTML(str) {
295     return str.
296         replace(/&/g, '&amp;').
297         replace(/</g, '&lt;').
298         replace(/>/g, '&gt;').
299         replace(/'/g, '&apos;').
300         replace(/"/g, '&quot;');
301 };
302
303 let terminal = {
304   initialize: function() {
305     this.rows = rows_selector.value;
306     this.cols = cols_selector.value;
307     this.pre_el = document.getElementById("terminal");
308     this.set_default_colors();
309     this.apply_colors();
310     this.content = [];
311       let line = []
312     for (let y = 0, x = 0; y <= this.rows; x++) {
313         if (x == this.cols) {
314             x = 0;
315             y += 1;
316             this.content.push(line);
317             line = [];
318             if (y == this.rows) {
319                 break;
320             }
321         }
322         line.push(' ');
323     }
324   },
325   apply_colors: function() {
326     this.pre_el.style.color = this.foreground;
327     this.pre_el.style.backgroundColor = this.background;
328   },
329   set_default_colors: function() {
330       this.foreground = 'white';
331       this.background = 'black';
332       this.apply_colors();
333   },
334   set_random_colors: function() {
335       function rand(offset) {
336           return Math.floor(offset + Math.random() * 96).toString(16).padStart(2, '0');
337       }
338       this.foreground = '#' + rand(159) + rand(159) + rand(159);
339       this.background = '#' + rand(0) + rand(0) + rand(0);
340       this.apply_colors();
341   },
342   blink_screen: function() {
343       this.pre_el.style.color = this.background;
344       this.pre_el.style.backgroundColor = this.foreground;
345       setTimeout(() => {
346           this.pre_el.style.color = this.foreground;
347           this.pre_el.style.backgroundColor = this.background;
348       }, 100);
349   },
350   refresh: function() {
351       let pre_content = '';
352       for (let y = 0; y < this.rows; y++) {
353           let line = this.content[y].join('');
354           let chunks = [];
355           if (y in tui.links) {
356               let start_x = 0;
357               for (let span of tui.links[y]) {
358                   chunks.push(escapeHTML(line.slice(start_x, span[0])));
359                   chunks.push('<a target="_blank" href="');
360                   chunks.push(escapeHTML(span[2]));
361                   chunks.push('">');
362                   chunks.push(escapeHTML(line.slice(span[0], span[1])));
363                   chunks.push('</a>');
364                   start_x = span[1];
365               }
366               chunks.push(escapeHTML(line.slice(start_x)));
367           } else {
368               chunks = [escapeHTML(line)];
369           }
370           for (const chunk of chunks) {
371               pre_content += chunk;
372           }
373           pre_content += '\n';
374       }
375       this.pre_el.innerHTML = pre_content;
376   },
377   write: function(start_y, start_x, msg) {
378       for (let x = start_x, i = 0; x < this.cols && i < msg.length; x++, i++) {
379           this.content[start_y][x] = msg[i];
380       }
381   },
382   drawBox: function(start_y, start_x, height, width) {
383     let end_y = start_y + height;
384     let end_x = start_x + width;
385     for (let y = start_y, x = start_x; y < this.rows; x++) {
386       if (x == end_x) {
387         x = start_x;
388         y += 1;
389         if (y == end_y) {
390             break;
391         }
392       };
393       this.content[y][x] = ' ';
394     }
395   },
396 }
397 terminal.initialize();
398
399 let parser = {
400   tokenize: function(str) {
401     let tokens = [];
402     let token = ''
403     let quoted = false;
404     let escaped = false;
405     for (let i = 0; i < str.length; i++) {
406       let c = str[i];
407       if (quoted) {
408         if (escaped) {
409           token += c;
410           escaped = false;
411         } else if (c == '\\') {
412           escaped = true;
413         } else if (c == '"') {
414           quoted = false
415         } else {
416           token += c;
417         }
418       } else if (c == '"') {
419         quoted = true
420       } else if (c === ' ') {
421         if (token.length > 0) {
422           tokens.push(token);
423           token = '';
424         }
425       } else {
426         token += c;
427       }
428     }
429     if (token.length > 0) {
430       tokens.push(token);
431     }
432     return tokens;
433   },
434   parse_yx: function(position_string) {
435     let coordinate_strings = position_string.split(',')
436     let position = [0, 0];
437     position[0] = parseInt(coordinate_strings[0].slice(2));
438     position[1] = parseInt(coordinate_strings[1].slice(2));
439     return position;
440   },
441 }
442
443 class Thing {
444     constructor(yx) {
445         this.position = yx;
446     }
447 }
448
449 let server = {
450     init: function(url) {
451         this.url = url;
452         this.websocket = new WebSocket(this.url);
453         this.websocket.onopen = function(event) {
454             game.thing_types = {};
455             game.terrains = {};
456             server.send(['TASKS']);
457             server.send(['TERRAINS']);
458             server.send(['THING_TYPES']);
459             tui.log_msg("@ server connected! :)");
460             tui.switch_mode('login');
461         };
462         this.websocket.onclose = function(event) {
463             tui.switch_mode('waiting_for_server');
464             tui.log_msg("@ server disconnected :(");
465         };
466             this.websocket.onmessage = this.handle_event;
467         },
468     reconnect_to: function(url) {
469         this.websocket.close();
470         this.init(url);
471     },
472     send: function(tokens) {
473         this.websocket.send(unparser.untokenize(tokens));
474     },
475     handle_event: function(event) {
476         let tokens = parser.tokenize(event.data);
477         if (tokens[0] === 'TURN') {
478             game.turn_complete = false;
479             game.turn = parseInt(tokens[1]);
480         } else if (tokens[0] === 'PSEUDO_FOV_WIPE') {
481             game.portals_new = {};
482             explorer.annotations_new = {};
483             game.things_new = [];
484         } else if (tokens[0] === 'THING') {
485             let t = game.get_thing_temp(tokens[4], true);
486             t.position = parser.parse_yx(tokens[1]);
487             t.type_ = tokens[2];
488             t.protection = tokens[3];
489             t.portable = parseInt(tokens[5]);
490             t.commandable = parseInt(tokens[6]);
491         } else if (tokens[0] === 'THING_NAME') {
492             let t = game.get_thing_temp(tokens[1]);
493             t.name_ = tokens[2];
494         } else if (tokens[0] === 'THING_FACE') {
495             let t = game.get_thing_temp(tokens[1]);
496             t.face = tokens[2];
497         } else if (tokens[0] === 'THING_HAT') {
498             let t = game.get_thing_temp(tokens[1]);
499             t.hat = tokens[2];
500         } else if (tokens[0] === 'THING_CHAR') {
501             let t = game.get_thing_temp(tokens[1]);
502             t.thing_char = tokens[2];
503         } else if (tokens[0] === 'TASKS') {
504             game.tasks = tokens[1].split(',');
505             tui.mode_write.legal = game.tasks.includes('WRITE');
506             tui.mode_command_thing.legal = game.tasks.includes('WRITE');
507             tui.mode_take_thing.legal = game.tasks.includes('PICK_UP');
508             tui.mode_drop_thing.legal = game.tasks.includes('DROP');
509         } else if (tokens[0] === 'THING_TYPE') {
510             game.thing_types[tokens[1]] = tokens[2]
511         } else if (tokens[0] === 'THING_CARRYING') {
512             let t = game.get_thing_temp(tokens[1]);
513             t.carrying = game.get_thing(tokens[2], false);
514         } else if (tokens[0] === 'THING_INSTALLED') {
515             let t = game.get_thing_temp(tokens[1]);
516             t.installed = true;
517         } else if (tokens[0] === 'TERRAIN') {
518             game.terrains[tokens[1]] = tokens[2]
519         } else if (tokens[0] === 'MAP') {
520             game.map_geometry_new = tokens[1];
521             game.map_size_new = parser.parse_yx(tokens[2]);
522             game.map_new = tokens[3]
523         } else if (tokens[0] === 'FOV') {
524             game.fov_new = tokens[1]
525         } else if (tokens[0] === 'MAP_CONTROL') {
526             game.map_control_new = tokens[1]
527         } else if (tokens[0] === 'GAME_STATE_COMPLETE') {
528             game.portals = game.portals_new;
529             game.map_geometry = game.map_geometry_new;
530             game.map_size = game.map_size_new;
531             game.map = game.map_new;
532             game.fov = game.fov_new;
533             tui.init_keys();
534             game.map_control = game.map_control_new;
535             explorer.annotations = explorer.annotations_new;
536             explorer.info_cached = false;
537             game.things = game.things_new;
538             game.player = game.things[game.player_id];
539             game.turn_complete = true;
540             if (tui.mode.name == 'post_login_wait') {
541                 tui.switch_mode('play');
542             } else {
543                 tui.full_refresh();
544             }
545         } else if (tokens[0] === 'CHAT') {
546              tui.log_msg('# ' + tokens[1], 1);
547         } else if (tokens[0] === 'CHATFACE') {
548             tui.draw_face = tokens[1];
549             tui.full_refresh();
550         } else if (tokens[0] === 'REPLY') {
551              tui.log_msg('#MUSICPLAYER: ' + tokens[1], 1);
552         } else if (tokens[0] === 'PLAYER_ID') {
553             game.player_id = parseInt(tokens[1]);
554         } else if (tokens[0] === 'LOGIN_OK') {
555             this.send(['GET_GAMESTATE']);
556             tui.switch_mode('post_login_wait');
557         } else if (tokens[0] === 'DEFAULT_COLORS') {
558             terminal.set_default_colors();
559         } else if (tokens[0] === 'RANDOM_COLORS') {
560             terminal.set_random_colors();
561         } else if (tokens[0] === 'ADMIN_OK') {
562             tui.is_admin = true;
563             tui.log_msg('@ you now have admin rights');
564             tui.switch_mode('admin');
565         } else if (tokens[0] === 'PORTAL') {
566             let position = parser.parse_yx(tokens[1]);
567             game.portals_new[position] = tokens[2];
568         } else if (tokens[0] === 'ANNOTATION') {
569             let position = parser.parse_yx(tokens[1]);
570             explorer.annotations_new[position] = tokens[2];
571         } else if (tokens[0] === 'UNHANDLED_INPUT') {
572             tui.log_msg('? unknown command');
573         } else if (tokens[0] === 'PLAY_ERROR') {
574             tui.log_msg('? ' + tokens[1]);
575             terminal.blink_screen();
576         } else if (tokens[0] === 'ARGUMENT_ERROR') {
577             tui.log_msg('? syntax error: ' + tokens[1]);
578         } else if (tokens[0] === 'GAME_ERROR') {
579             tui.log_msg('? game error: ' + tokens[1]);
580         } else if (tokens[0] === 'PONG') {
581             ;
582         } else {
583             tui.log_msg('? unhandled input: ' + event.data);
584         }
585     }
586 }
587
588 let unparser = {
589     quote: function(str) {
590         let quoted = ['"'];
591         for (let i = 0; i < str.length; i++) {
592             let c = str[i];
593             if (['"', '\\'].includes(c)) {
594                 quoted.push('\\');
595             };
596             quoted.push(c);
597         }
598         quoted.push('"');
599         return quoted.join('');
600     },
601     to_yx: function(yx_coordinate) {
602         return "Y:" + yx_coordinate[0] + ",X:" + yx_coordinate[1];
603     },
604     untokenize: function(tokens) {
605         let quoted_tokens = [];
606         for (let token of tokens) {
607             quoted_tokens.push(this.quote(token));
608         }
609         return quoted_tokens.join(" ");
610     }
611 }
612
613 class Mode {
614     constructor(name, has_input_prompt=false, shows_info=false,
615                 is_intro=false, is_single_char_entry=false) {
616         this.name = name;
617         this.short_desc = mode_helps[name].short;
618         this.available_modes = [];
619         this.available_actions = [];
620         this.has_input_prompt = has_input_prompt;
621         this.shows_info= shows_info;
622         this.is_intro = is_intro;
623         this.help_intro = mode_helps[name].long;
624         this.intro_msg = mode_helps[name].intro;
625         this.is_single_char_entry = is_single_char_entry;
626         this.legal = true;
627     }
628     *iter_available_modes() {
629         for (let mode_name of this.available_modes) {
630             let mode = tui['mode_' + mode_name];
631             if (!mode.legal) {
632                 continue;
633             }
634             let key = tui.keys['switch_to_' + mode.name];
635             yield [mode, key]
636         }
637     }
638     list_available_modes() {
639         let msg = ''
640         if (this.available_modes.length > 0) {
641             msg += 'Other modes available from here:\n';
642             for (let [mode, key] of this.iter_available_modes()) {
643                 msg += '[' + key + '] – ' + mode.short_desc + '\n';
644             }
645         }
646         return msg;
647     }
648     mode_switch_on_key(key_event) {
649         for (let [mode, key] of this.iter_available_modes()) {
650             if (key_event.key == key) {
651                 event.preventDefault();
652                 tui.switch_mode(mode.name);
653                 return true;
654             };
655         }
656         return false;
657     }
658 }
659 let tui = {
660   links: {},
661   log: [],
662   input_prompt: '> ',
663   input_lines: [],
664   window_width: terminal.cols / 2,
665   height_turn_line: 1,
666   height_mode_line: 1,
667   height_input: 1,
668   password: 'foo',
669   show_help: false,
670   is_admin: false,
671   tile_draw: false,
672   mode_waiting_for_server: new Mode('waiting_for_server',
673                                      false, false, true),
674   mode_login: new Mode('login', true, false, true),
675   mode_post_login_wait: new Mode('post_login_wait'),
676   mode_chat: new Mode('chat', true),
677   mode_annotate: new Mode('annotate', true, true),
678   mode_play: new Mode('play'),
679   mode_study: new Mode('study', false, true),
680   mode_write: new Mode('write', false, false, false, true),
681   mode_edit: new Mode('edit'),
682   mode_control_pw_type: new Mode('control_pw_type', true),
683   mode_admin_thing_protect: new Mode('admin_thing_protect', true),
684   mode_portal: new Mode('portal', true, true),
685   mode_password: new Mode('password', true),
686   mode_name_thing: new Mode('name_thing', true, true),
687   mode_command_thing: new Mode('command_thing', true),
688   mode_take_thing: new Mode('take_thing', true),
689   mode_drop_thing: new Mode('drop_thing', true),
690   mode_enter_face: new Mode('enter_face', true),
691   mode_admin_enter: new Mode('admin_enter', true),
692   mode_admin: new Mode('admin'),
693   mode_control_pw_pw: new Mode('control_pw_pw', true),
694   mode_control_tile_type: new Mode('control_tile_type', true),
695   mode_control_tile_draw: new Mode('control_tile_draw'),
696   action_tasks: {
697       'flatten': 'FLATTEN_SURROUNDINGS',
698       'take_thing': 'PICK_UP',
699       'drop_thing': 'DROP',
700       'move': 'MOVE',
701       'door': 'DOOR',
702       'install': 'INSTALL',
703       'wear': 'WEAR',
704       'command': 'COMMAND',
705       'consume': 'INTOXICATE',
706       'spin': 'SPIN',
707   },
708   offset: [0,0],
709   map_lines: [],
710   selectables: [],
711   draw_face: false,
712   init: function() {
713       this.mode_play.available_modes = ["chat", "study", "edit", "admin_enter",
714                                         "command_thing", "take_thing", "drop_thing"]
715       this.mode_play.available_actions = ["move", "teleport", "door", "consume",
716                                           "wear", "spin"];
717       this.mode_study.available_modes = ["chat", "play", "admin_enter", "edit"]
718       this.mode_study.available_actions = ["toggle_map_mode", "move_explorer"];
719       this.mode_admin.available_modes = ["admin_thing_protect", "control_pw_type",
720                                          "control_tile_type", "chat",
721                                          "study", "play", "edit"]
722       this.mode_admin.available_actions = ["move"];
723       this.mode_control_tile_draw.available_modes = ["admin_enter"]
724       this.mode_control_tile_draw.available_actions = ["toggle_tile_draw"];
725       this.mode_edit.available_modes = ["write", "annotate", "portal", "name_thing",
726                                         "password", "chat", "study", "play",
727                                         "admin_enter", "enter_face"]
728       this.mode_edit.available_actions = ["move", "flatten", "install",
729                                           "toggle_map_mode"]
730       this.inputEl = document.getElementById("input");
731       this.switch_mode('waiting_for_server');
732       this.recalc_input_lines();
733       this.height_header = this.height_turn_line + this.height_mode_line;
734       this.init_keys();
735   },
736   init_keys: function() {
737     document.getElementById("move_table").hidden = true;
738     this.keys = {};
739     for (let key_selector of key_selectors) {
740         this.keys[key_selector.id.slice(4)] = key_selector.value;
741     }
742     this.movement_keys = {};
743     let geometry_prefix = 'undefinedMapGeometry_';
744     if (game.map_geometry) {
745         geometry_prefix = game.map_geometry.toLowerCase() + '_';
746     }
747     for (const key_name of Object.keys(key_descriptions)) {
748         if (key_name.startsWith(geometry_prefix)) {
749             let direction = key_name.split('_')[2].toUpperCase();
750             let key = this.keys[key_name];
751             this.movement_keys[key] = direction;
752         }
753     };
754     for (const move_button of document.querySelectorAll('[id*="_move_"]')) {
755         if (move_button.id.startsWith('key_')) {
756             continue;
757         }
758         move_button.hidden = true;
759     };
760     for (const move_button of document.querySelectorAll('[id^="' + geometry_prefix + 'move_"]')) {
761         document.getElementById("move_table").hidden = false;
762         move_button.hidden = false;
763     };
764     for (let el of document.getElementsByTagName("button")) {
765       let action_desc = key_descriptions[el.id];
766       let action_key = '[' + this.keys[el.id] + ']';
767       el.innerHTML = escapeHTML(action_desc) + '<br /><span class="keyboard_controlled">' + escapeHTML(action_key) + '</span>';
768     }
769   },
770   task_action_on: function(action) {
771       return game.tasks.includes(this.action_tasks[action]);
772   },
773   switch_mode: function(mode_name) {
774
775     function fail(msg, return_mode) {
776         tui.log_msg('? ' + msg);
777         terminal.blink_screen();
778         tui.switch_mode(return_mode);
779     }
780
781     if (this.mode && this.mode.name == 'control_tile_draw') {
782         tui.log_msg('@ finished tile protection drawing.')
783     }
784     this.draw_face = false;
785     this.tile_draw = false;
786       if (mode_name == 'command_thing' && (!game.player.carrying
787                                            || !game.player.carrying.commandable)) {
788         return fail('not carrying anything commandable', 'play');
789     };
790     if (mode_name == 'take_thing' && game.player.carrying) {
791         return fail('already carrying something', 'play');
792     };
793     if (mode_name == 'drop_thing' && !game.player.carrying) {
794         return fail('not carrying anything droppable', 'play');
795     }
796     if (mode_name == 'admin_enter' && this.is_admin) {
797         mode_name = 'admin';
798     } else if (['name_thing', 'admin_thing_protect'].includes(mode_name)) {
799         let thing_id = null;
800         for (let t_id in game.things) {
801             if (t_id == game.player_id) {
802                 continue;
803             }
804             let t = game.things[t_id];
805             if (game.player.position[0] == t.position[0]
806                 && game.player.position[1] == t.position[1]) {
807                 thing_id = t_id;
808                 break;
809             }
810         }
811         if (!thing_id) {
812             return fail('not standing over thing', 'fail');
813         } else {
814             this.selected_thing_id = thing_id;
815         }
816     };
817     this.mode = this['mode_' + mode_name];
818     if (["control_tile_draw", "control_tile_type", "control_pw_type"].includes(this.mode.name)) {
819         this.map_mode = 'protections';
820     } else if (this.mode.name != "edit") {
821         this.map_mode = 'terrain + things';
822     };
823     if (game.player_id in game.things && (this.mode.shows_info || this.mode.name == 'control_tile_draw')) {
824         explorer.position = game.player.position;
825     }
826     this.inputEl.value = "";
827     this.restore_input_values();
828     for (let el of document.getElementsByTagName("button")) {
829         el.disabled = true;
830     }
831     document.getElementById("help").disabled = false;
832     for (const action of this.mode.available_actions) {
833         if (["move", "move_explorer"].includes(action)) {
834             for (const move_key of document.querySelectorAll('[id*="_move_"]')) {
835                 move_key.disabled = false;
836             }
837         } else if (Object.keys(this.action_tasks).includes(action)) {
838             if (this.task_action_on(action)) {
839                 document.getElementById(action).disabled = false;
840             }
841         } else {
842             document.getElementById(action).disabled = false;
843         };
844     }
845     for (const mode_name of this.mode.available_modes) {
846             document.getElementById('switch_to_' + mode_name).disabled = false;
847     }
848     if (this.mode.intro_msg.length > 0) {
849         this.log_msg(this.mode.intro_msg);
850     }
851     if (this.mode.name == 'login') {
852         if (this.login_name) {
853             server.send(['LOGIN', this.login_name]);
854         } else {
855             this.log_msg("? need login name");
856         }
857     } else if (this.mode.is_single_char_entry) {
858         this.show_help = true;
859     } else if (this.mode.name == 'take_thing') {
860         this.log_msg("Portable things in reach for pick-up:");
861         const y = game.player.position[0]
862         const x = game.player.position[1]
863         let select_range = [y.toString() + ':' + x.toString(),
864                             (y + 0).toString() + ':' + (x - 1).toString(),
865                             (y + 0).toString() + ':' + (x + 1).toString(),
866                             (y - 1).toString() + ':' + (x).toString(),
867                             (y + 1).toString() + ':' + (x).toString()];
868         if (game.map_geometry == 'Hex') {
869             if (y % 2) {
870                 select_range.push((y - 1).toString() + ':' + (x + 1).toString());
871                 select_range.push((y + 1).toString() + ':' + (x + 1).toString());
872             } else {
873                 select_range.push((y - 1).toString() + ':' + (x - 1).toString());
874                 select_range.push((y + 1).toString() + ':' + (x - 1).toString());
875             }
876         };
877         this.selectables = [];
878         for (const t_id in game.things) {
879             const t = game.things[t_id];
880             if (select_range.includes(t.position[0].toString()
881                                       + ':' + t.position[1].toString())
882                 && t.portable) {
883                 this.selectables.push(t_id);
884             }
885         };
886         if (this.selectables.length == 0) {
887             this.log_msg('none');
888             terminal.blink_screen();
889             this.switch_mode('play');
890             return;
891         } else {
892             for (let [i, t_id] of this.selectables.entries()) {
893                 const t = game.things[t_id];
894                 this.log_msg(i + ': ' + explorer.get_thing_info(t));
895             }
896         }
897     } else if (this.mode.name == 'drop_thing') {
898         this.log_msg('Direction to drop thing to:');
899         this.selectables = ['HERE'].concat(Object.values(this.movement_keys));
900         for (let [i, direction] of this.selectables.entries()) {
901             this.log_msg(i + ': ' + direction);
902         };
903     } else if (this.mode.name == 'command_thing') {
904         server.send(['TASK:COMMAND', 'HELP']);
905     } else if (this.mode.name == 'control_pw_pw') {
906         this.log_msg('@ enter protection password for "' + this.tile_control_char + '":');
907     } else if (this.mode.name == 'control_tile_draw') {
908         this.log_msg('@ can draw protection character "' + this.tile_control_char + '", turn drawing on/off with [' + this.keys.toggle_tile_draw + '], finish with [' +  this.keys.switch_to_admin_enter + '].')
909     }
910     this.full_refresh();
911   },
912   offset_links: function(offset, links) {
913       for (let y in links) {
914           let real_y = offset[0] + parseInt(y);
915           if (!this.links[real_y]) {
916               this.links[real_y] = [];
917           }
918           for (let link of links[y]) {
919               const offset_link = [link[0] + offset[1], link[1] + offset[1], link[2]];
920               this.links[real_y].push(offset_link);
921           }
922       }
923   },
924   restore_input_values: function() {
925       if (this.mode.name == 'annotate' && explorer.position in explorer.annotations) {
926           let info = explorer.annotations[explorer.position];
927           if (info != "(none)") {
928               this.inputEl.value = info;
929           }
930       } else if (this.mode.name == 'portal' && explorer.position in game.portals) {
931           let portal = game.portals[explorer.position]
932           this.inputEl.value = portal;
933       } else if (this.mode.name == 'password') {
934           this.inputEl.value = this.password;
935       } else if (this.mode.name == 'name_thing') {
936           let t = game.get_thing(this.selected_thing_id);
937           if (t && t.name_) {
938               this.inputEl.value = t.name_;
939           }
940       } else if (this.mode.name == 'admin_thing_protect') {
941           let t = game.get_thing(this.selected_thing_id);
942           if (t && t.protection) {
943               this.inputEl.value = t.protection;
944           }
945       }
946   },
947   recalc_input_lines: function() {
948       if (this.mode.has_input_prompt) {
949           let _ = null;
950           [this.input_lines, _] = this.msg_into_lines_of_width(this.input_prompt + this.inputEl.value, this.window_width);
951       } else {
952           this.input_lines = [];
953       }
954       this.height_input = this.input_lines.length;
955   },
956   msg_into_lines_of_width: function(msg, width) {
957       function push_inner_link(y, end_x) {
958           if (!inner_links[y]) {
959               inner_links[y] = [];
960           };
961           inner_links[y].push([url_start_x, end_x, url]);
962       };
963       const matches = msg.matchAll(/https?:\/\/[^\s]+/g)
964       let link_data = {};
965       let url_ends = [];
966       for (const match of matches) {
967           const url = match[0];
968           const url_start = match.index;
969           const url_end = match.index + match[0].length;
970           link_data[url_start] = url;
971           url_ends.push(url_end);
972       }
973       let url_start_x = 0;
974       let url = '';
975       let inner_links = {};
976       let in_link = false;
977       let chunk = "";
978       let lines = [];
979       for (let i = 0, x = 0, y = 0; i < msg.length; i++, x++) {
980           if (x >= width || msg[i] == "\n") {
981               if (in_link) {
982                   push_inner_link(y, chunk.length);
983                   url_start_x = 0;
984                   if (url_ends[0] == i) {
985                       in_link = false;
986                       url_ends.shift();
987                   }
988               };
989               lines.push(chunk);
990               chunk = "";
991               x = 0;
992               if (msg[i] == "\n") {
993                   x -= 1;
994               };
995               y += 1;
996           };
997           if (msg[i] != "\n") {
998               chunk += msg[i];
999           };
1000           if (i in link_data) {
1001               url_start_x = x;
1002               url = link_data[i];
1003               in_link = true;
1004           } else if (url_ends[0] == i) {
1005               url_ends.shift();
1006               push_inner_link(y, x);
1007               in_link = false;
1008           }
1009       }
1010       lines.push(chunk);
1011       if (in_link) {
1012           push_inner_link(lines.length - 1, chunk.length);
1013       }
1014       return [lines, inner_links];
1015   },
1016   log_msg: function(msg) {
1017       this.log.push(msg);
1018       while (this.log.length > 100) {
1019         this.log.shift();
1020       };
1021       this.full_refresh();
1022   },
1023   pick_selectable: function(task_name) {
1024       const i = parseInt(this.inputEl.value);
1025       if (isNaN(i) || i < 0 || i >= this.selectables.length) {
1026           tui.log_msg('? invalid index, aborted');
1027       } else {
1028           server.send(['TASK:' + task_name, tui.selectables[i]]);
1029       }
1030       this.inputEl.value = "";
1031       this.switch_mode('play');
1032   },
1033   draw_map: function() {
1034     if (!game.turn_complete && this.map_lines.length == 0) {
1035         return;
1036     }
1037     if (game.turn_complete) {
1038         let map_lines_split = [];
1039         let line = [];
1040         for (let i = 0, j = 0; i < game.map.length; i++, j++) {
1041             if (j == game.map_size[1]) {
1042                 map_lines_split.push(line);
1043                 line = [];
1044                 j = 0;
1045             };
1046             if (this.map_mode == 'protections') {
1047                 line.push(game.map_control[i] + ' ');
1048             } else {
1049                 line.push(game.map[i] + ' ');
1050             }
1051         };
1052         map_lines_split.push(line);
1053         if (this.map_mode == 'terrain + annotations') {
1054             for (const [coordinate, _] of Object.entries(explorer.annotations)) {
1055                 const yx = coordinate.split(',')
1056                 map_lines_split[yx[0]][yx[1]] = 'A ';
1057             }
1058         } else if (this.map_mode == 'terrain + things') {
1059             for (const p in game.portals) {
1060                 let coordinate = p.split(',')
1061                 let original = map_lines_split[coordinate[0]][coordinate[1]];
1062                 map_lines_split[coordinate[0]][coordinate[1]] = original[0] + 'P';
1063             }
1064             let used_positions = [];
1065             function draw_thing(t, used_positions) {
1066                 let symbol = game.thing_types[t.type_];
1067                 let meta_char = ' ';
1068                 if (t.thing_char) {
1069                     meta_char = t.thing_char;
1070                 }
1071                 if (used_positions.includes(t.position.toString())) {
1072                     meta_char = '+';
1073                 };
1074                 if (t.carrying) {
1075                     meta_char = '$';
1076                 }
1077                 map_lines_split[t.position[0]][t.position[1]] = symbol + meta_char;
1078                 used_positions.push(t.position.toString());
1079             }
1080             for (const thing_id in game.things) {
1081                 let t = game.things[thing_id];
1082                 if (t.type_ != 'Player') {
1083                     draw_thing(t, used_positions);
1084                 }
1085             };
1086             for (const thing_id in game.things) {
1087                 let t = game.things[thing_id];
1088                 if (t.type_ == 'Player') {
1089                     draw_thing(t, used_positions);
1090                 }
1091             };
1092         }
1093         if (tui.mode.shows_info || tui.mode.name == 'control_tile_draw') {
1094             map_lines_split[explorer.position[0]][explorer.position[1]] = '??';
1095         } else if (tui.map_mode != 'terrain + things') {
1096             map_lines_split[game.player.position[0]][game.player.position[1]] = '??';
1097         }
1098         this.map_lines = []
1099         if (game.map_geometry == 'Square') {
1100             for (let line_split of map_lines_split) {
1101                 this.map_lines.push(line_split.join(''));
1102             };
1103         } else if (game.map_geometry == 'Hex') {
1104             let indent = 0
1105             for (let line_split of map_lines_split) {
1106                 this.map_lines.push(' '.repeat(indent) + line_split.join(''));
1107                 if (indent == 0) {
1108                     indent = 1;
1109                 } else {
1110                     indent = 0;
1111                 };
1112             };
1113         }
1114         let window_center = [terminal.rows / 2, this.window_width / 2];
1115         let center_position = [game.player.position[0], game.player.position[1]];
1116         if (tui.mode.shows_info || tui.mode.name == 'control_tile_draw') {
1117             center_position = [explorer.position[0], explorer.position[1]];
1118         }
1119         center_position[1] = center_position[1] * 2;
1120         this.offset = [center_position[0] - window_center[0],
1121                        center_position[1] - window_center[1]]
1122         if (game.map_geometry == 'Hex' && this.offset[0] % 2) {
1123             this.offset[1] += 1;
1124         };
1125     };
1126     let term_y = Math.max(0, -this.offset[0]);
1127     let term_x = Math.max(0, -this.offset[1]);
1128     let map_y = Math.max(0, this.offset[0]);
1129     let map_x = Math.max(0, this.offset[1]);
1130     for (; term_y < terminal.rows && map_y < this.map_lines.length; term_y++, map_y++) {
1131         let to_draw = this.map_lines[map_y].slice(map_x, this.window_width + this.offset[1]);
1132         terminal.write(term_y, term_x, to_draw);
1133     }
1134   },
1135   draw_face_popup: function() {
1136       const t = game.things[this.draw_face];
1137       if (!t || !t.face) {
1138           this.draw_face = false;
1139           return;
1140       }
1141       const start_x = tui.window_width - 10;
1142       let t_char = ' ';
1143       if (t.thing_char) {
1144           t_char = t.thing_char;
1145       }
1146       function draw_body_part(body_part, end_y) {
1147           terminal.write(end_y - 4, start_x, ' _[ @' + t_char + ' ]_ ');
1148           terminal.write(end_y - 3, start_x, '|        |');
1149           terminal.write(end_y - 2, start_x, '| ' + body_part.slice(0, 6) + ' |');
1150           terminal.write(end_y - 1, start_x, '| ' + body_part.slice(6, 12) + ' |');
1151           terminal.write(end_y, start_x, '| ' + body_part.slice(12, 18) + ' |');
1152       }
1153       if (t.face) {
1154           draw_body_part(t.face, terminal.rows - 2);
1155       }
1156       if (t.hat) {
1157           draw_body_part(t.hat, terminal.rows - 5);
1158       }
1159       terminal.write(terminal.rows - 1, start_x, '|        |');
1160   },
1161   draw_mode_line: function() {
1162       let help = 'hit [' + this.keys.help + '] for help';
1163       if (this.mode.has_input_prompt) {
1164           help = 'enter /help for help';
1165       }
1166       terminal.write(0, this.window_width, 'MODE: ' + this.mode.short_desc + ' – ' + help);
1167   },
1168   draw_turn_line: function(n) {
1169       if (game.turn_complete) {
1170           terminal.write(1, this.window_width, 'TURN: ' + game.turn);
1171       }
1172   },
1173   draw_history: function() {
1174       let log_display_lines = [];
1175       let log_links = {};
1176       let y_offset_in_log = 0;
1177       for (let line of this.log) {
1178           let [new_lines, link_data] = this.msg_into_lines_of_width(line,
1179                                                                     this.window_width)
1180           log_display_lines = log_display_lines.concat(new_lines);
1181           for (const y in link_data) {
1182               const rel_y = y_offset_in_log + parseInt(y);
1183               log_links[rel_y] = [];
1184               for (let link of link_data[y]) {
1185                   log_links[rel_y].push(link);
1186               }
1187           }
1188           y_offset_in_log += new_lines.length;
1189       };
1190       let i = log_display_lines.length - 1;
1191       for (let y = terminal.rows - 1 - this.height_input;
1192            y >= this.height_header && i >= 0;
1193            y--, i--) {
1194           terminal.write(y, this.window_width, log_display_lines[i]);
1195       }
1196       for (const key of Object.keys(log_links)) {
1197           if (parseInt(key) <= i) {
1198               delete log_links[key];
1199           }
1200       }
1201       let offset = [terminal.rows - this.height_input - log_display_lines.length,
1202                     this.window_width];
1203       this.offset_links(offset, log_links);
1204   },
1205   draw_info: function() {
1206       const info = "MAP VIEW: " + tui.map_mode + "\n" + explorer.get_info();
1207       let [lines, link_data] = this.msg_into_lines_of_width(info, this.window_width);
1208       let offset = [this.height_header, this.window_width];
1209       for (let y = offset[0], i = 0; y < terminal.rows && i < lines.length; y++, i++) {
1210         terminal.write(y, offset[1], lines[i]);
1211       }
1212       this.offset_links(offset, link_data);
1213   },
1214   draw_input: function() {
1215     if (this.mode.has_input_prompt) {
1216         for (let y = terminal.rows - this.height_input, i = 0; i < this.input_lines.length; y++, i++) {
1217             terminal.write(y, this.window_width, this.input_lines[i]);
1218         }
1219     }
1220   },
1221   draw_help: function() {
1222       let movement_keys_desc = '';
1223       if (!this.mode.is_intro) {
1224           movement_keys_desc = Object.keys(this.movement_keys).join(',');
1225       }
1226       let content = this.mode.short_desc + " help\n\n" + this.mode.help_intro + "\n\n";
1227       if (this.mode.available_actions.length > 0) {
1228           content += "Available actions:\n";
1229           for (let action of this.mode.available_actions) {
1230               if (Object.keys(this.action_tasks).includes(action)) {
1231                   if (!this.task_action_on(action)) {
1232                       continue;
1233                   }
1234               }
1235               if (action == 'move_explorer') {
1236                   action = 'move';
1237               }
1238               if (action == 'move') {
1239                   content += "[" + movement_keys_desc + "] – move\n"
1240               } else {
1241                   content += "[" + this.keys[action] + "] – " + key_descriptions[action] + "\n";
1242               }
1243           }
1244           content += '\n';
1245       }
1246       content += this.mode.list_available_modes();
1247       let start_x = 0;
1248       if (!this.mode.has_input_prompt) {
1249           start_x = this.window_width;
1250           this.draw_links = false;
1251       }
1252       terminal.drawBox(0, start_x, terminal.rows, this.window_width);
1253       let [lines, _] = this.msg_into_lines_of_width(content, this.window_width);
1254       for (let y = 0, i = 0; y < terminal.rows && i < lines.length; y++, i++) {
1255           terminal.write(y, start_x, lines[i]);
1256       }
1257   },
1258   toggle_tile_draw: function() {
1259       if (tui.tile_draw) {
1260           tui.tile_draw = false;
1261       } else {
1262           tui.tile_draw = true;
1263       }
1264   },
1265   toggle_map_mode: function() {
1266       if (tui.map_mode == 'terrain only') {
1267           tui.map_mode = 'terrain + annotations';
1268       } else if (tui.map_mode == 'terrain + annotations') {
1269           tui.map_mode = 'terrain + things';
1270       } else if (tui.map_mode == 'terrain + things') {
1271           tui.map_mode = 'protections';
1272       } else if (tui.map_mode == 'protections') {
1273           tui.map_mode = 'terrain only';
1274       }
1275   },
1276   full_refresh: function() {
1277     this.draw_links = true;
1278     this.links = {};
1279     terminal.drawBox(0, 0, terminal.rows, terminal.cols);
1280     this.recalc_input_lines();
1281     if (this.mode.is_intro) {
1282         this.draw_history();
1283         this.draw_input();
1284     } else {
1285         this.draw_map();
1286         this.draw_turn_line();
1287         this.draw_mode_line();
1288         if (this.mode.shows_info) {
1289           this.draw_info();
1290         } else {
1291           this.draw_history();
1292         }
1293         this.draw_input();
1294     }
1295     if (this.show_help) {
1296         this.draw_help();
1297     }
1298     if (this.draw_face && ['chat', 'play'].includes(this.mode.name)) {
1299         this.draw_face_popup();
1300     }
1301     if (!this.draw_links) {
1302         this.links = {};
1303     }
1304     terminal.refresh();
1305   }
1306 }
1307
1308 let game = {
1309     init: function() {
1310         this.turn = -1;
1311         this.player_id = -1;
1312         this.tasks = {};
1313         this.things = {};
1314         this.things_new = {};
1315         this.fov = "";
1316         this.fov_new = "";
1317         this.map = "";
1318         this.map_new = "";
1319         this.map_control = "";
1320         this.map_control_new = "";
1321         this.map_size = [0,0];
1322         this.map_size_new = [0,0];
1323         this.portals = {};
1324         this.portals_new = {};
1325     },
1326     get_thing_temp: function(id_, create_if_not_found=false) {
1327         if (id_ in game.things_new) {
1328             return game.things_new[id_];
1329         } else if (create_if_not_found) {
1330             let t = new Thing([0,0]);
1331             game.things_new[id_] = t;
1332             return t;
1333         };
1334     },
1335     get_thing: function(id_, create_if_not_found=false) {
1336         if (id_ in game.things) {
1337             return game.things[id_];
1338         };
1339     },
1340     move: function(start_position, direction) {
1341         let target = [start_position[0], start_position[1]];
1342         if (direction == 'LEFT') {
1343             target[1] -= 1;
1344         } else if (direction == 'RIGHT') {
1345             target[1] += 1;
1346         } else if (game.map_geometry == 'Square') {
1347             if (direction == 'UP') {
1348                 target[0] -= 1;
1349             } else if (direction == 'DOWN') {
1350                 target[0] += 1;
1351             };
1352         } else if (game.map_geometry == 'Hex') {
1353             let start_indented = start_position[0] % 2;
1354             if (direction == 'UPLEFT') {
1355                 target[0] -= 1;
1356                 if (!start_indented) {
1357                     target[1] -= 1;
1358                 }
1359             } else if (direction == 'UPRIGHT') {
1360                 target[0] -= 1;
1361                 if (start_indented) {
1362                     target[1] += 1;
1363                 }
1364             } else if (direction == 'DOWNLEFT') {
1365                 target[0] += 1;
1366                 if (!start_indented) {
1367                     target[1] -= 1;
1368                 }
1369             } else if (direction == 'DOWNRIGHT') {
1370                 target[0] += 1;
1371                 if (start_indented) {
1372                     target[1] += 1;
1373                 }
1374             };
1375         };
1376         if (target[0] < 0 || target[1] < 0 ||
1377             target[0] >= this.map_size[0] || target[1] >= this.map_size[1]) {
1378             return null;
1379         };
1380         return target;
1381     },
1382     teleport: function() {
1383         if (game.player.position in this.portals) {
1384             server.reconnect_to(this.portals[game.player.position]);
1385         } else {
1386             terminal.blink_screen();
1387             tui.log_msg('? not standing on portal')
1388         }
1389     }
1390 }
1391
1392 game.init();
1393 tui.init();
1394 tui.full_refresh();
1395 server.init(websocket_location);
1396
1397 let explorer = {
1398     position: [0,0],
1399     annotations: {},
1400     annotations_new: {},
1401     info_cached: false,
1402     move: function(direction) {
1403         let target = game.move(this.position, direction);
1404         if (target) {
1405             this.position = target
1406             this.info_cached = false;
1407             if (tui.tile_draw) {
1408                 this.send_tile_control_command();
1409             }
1410         } else {
1411             terminal.blink_screen();
1412         };
1413     },
1414     get_info: function() {
1415         if (this.info_cached) {
1416             return this.info_cached;
1417         }
1418         let info_to_cache = '';
1419         let position_i = this.position[0] * game.map_size[1] + this.position[1];
1420         if (game.fov[position_i] != '.') {
1421             info_to_cache += 'outside field of view';
1422         } else {
1423             for (let t_id in game.things) {
1424                  let t = game.things[t_id];
1425                  if (t.position[0] == this.position[0] && t.position[1] == this.position[1]) {
1426                      info_to_cache += "THING: " + this.get_thing_info(t);
1427                      let protection = t.protection;
1428                      if (protection == '.') {
1429                          protection = 'none';
1430                      }
1431                      info_to_cache += " / protection: " + protection + "\n";
1432                      if (t.hat) {
1433                          info_to_cache += t.hat.slice(0, 6) + '\n';
1434                          info_to_cache += t.hat.slice(6, 12) + '\n';
1435                          info_to_cache += t.hat.slice(12, 18) + '\n';
1436                      }
1437                      if (t.face) {
1438                          info_to_cache += t.face.slice(0, 6) + '\n';
1439                          info_to_cache += t.face.slice(6, 12) + '\n';
1440                          info_to_cache += t.face.slice(12, 18) + '\n';
1441                      }
1442                  }
1443             }
1444             let terrain_char = game.map[position_i]
1445             let terrain_desc = '?'
1446             if (game.terrains[terrain_char]) {
1447                 terrain_desc = game.terrains[terrain_char];
1448             };
1449             info_to_cache += 'TERRAIN: "' + terrain_char + '" / ' + terrain_desc + "\n";
1450             let protection = game.map_control[position_i];
1451             if (protection == '.') {
1452                 protection = 'unprotected';
1453             };
1454             info_to_cache += 'PROTECTION: ' + protection + '\n';
1455             if (this.position in game.portals) {
1456                 info_to_cache += "PORTAL: " + game.portals[this.position] + "\n";
1457             }
1458             if (this.position in this.annotations) {
1459                 info_to_cache += "ANNOTATION: " + this.annotations[this.position];
1460             }
1461         }
1462         this.info_cached = info_to_cache;
1463         return this.info_cached;
1464     },
1465     get_thing_info: function(t) {
1466         const symbol = game.thing_types[t.type_];
1467         let info = t.type_ + " / " + symbol;
1468         if (t.thing_char) {
1469             info += t.thing_char;
1470         };
1471         if (t.name_) {
1472             info += " (" + t.name_ + ")";
1473         }
1474         if (t.installed) {
1475             info += " / installed";
1476         }
1477         return info;
1478     },
1479     annotate: function(msg) {
1480         if (msg.length == 0) {
1481             msg = " ";  // triggers annotation deletion
1482         }
1483         server.send(["ANNOTATE", unparser.to_yx(explorer.position), msg, tui.password]);
1484     },
1485     set_portal: function(msg) {
1486         if (msg.length == 0) {
1487             msg = " ";  // triggers portal deletion
1488         }
1489         server.send(["PORTAL", unparser.to_yx(explorer.position), msg, tui.password]);
1490     },
1491     send_tile_control_command: function() {
1492         server.send(["SET_TILE_CONTROL", unparser.to_yx(this.position), tui.tile_control_char]);
1493     }
1494 }
1495
1496 tui.inputEl.addEventListener('input', (event) => {
1497     if (tui.mode.has_input_prompt) {
1498         let max_length = tui.window_width * terminal.rows - tui.input_prompt.length;
1499         if (tui.inputEl.value.length > max_length) {
1500             tui.inputEl.value = tui.inputEl.value.slice(0, max_length);
1501         };
1502     } else if (tui.mode.name == 'write' && tui.inputEl.value.length > 0) {
1503         server.send(["TASK:WRITE", tui.inputEl.value[0], tui.password]);
1504         tui.switch_mode('edit');
1505     }
1506     tui.full_refresh();
1507 }, false);
1508 document.onclick = function() {
1509     if (!tui.mode.is_single_char_entry) {
1510         tui.show_help = false;
1511     }
1512 };
1513 tui.inputEl.addEventListener('keydown', (event) => {
1514     tui.show_help = false;
1515     if (event.key == 'Enter') {
1516         event.preventDefault();
1517     }
1518     if ((!tui.mode.is_intro && event.key == 'Escape')
1519         || (tui.mode.has_input_prompt && event.key == 'Enter'
1520             && tui.inputEl.value.length == 0
1521             && ['chat', 'command_thing', 'take_thing', 'drop_thing',
1522                 'admin_enter'].includes(tui.mode.name))) {
1523         if (!['chat', 'play', 'study', 'edit'].includes(tui.mode.name)) {
1524             tui.log_msg('@ aborted');
1525         }
1526         tui.switch_mode('play');
1527     } else if (tui.mode.has_input_prompt && event.key == 'Enter' && tui.inputEl.value == '/help') {
1528         tui.show_help = true;
1529         tui.inputEl.value = "";
1530         tui.restore_input_values();
1531     } else if (!tui.mode.has_input_prompt && event.key == tui.keys.help
1532                && !tui.mode.is_single_char_entry) {
1533         tui.show_help = true;
1534     } else if (tui.mode.name == 'login' && event.key == 'Enter') {
1535         tui.login_name = tui.inputEl.value;
1536         server.send(['LOGIN', tui.inputEl.value]);
1537         tui.inputEl.value = "";
1538     } else if (tui.mode.name == 'enter_face' && event.key == 'Enter') {
1539         if (tui.inputEl.value.length != 18) {
1540             tui.log_msg('? wrong input length, aborting');
1541         } else {
1542             server.send(['PLAYER_FACE', tui.inputEl.value]);
1543         }
1544         tui.inputEl.value = "";
1545         tui.switch_mode('edit');
1546     } else if (tui.mode.name == 'command_thing' && event.key == 'Enter') {
1547         server.send(['TASK:COMMAND', tui.inputEl.value]);
1548         tui.inputEl.value = "";
1549     } else if (tui.mode.name == 'take_thing' && event.key == 'Enter') {
1550         tui.pick_selectable('PICK_UP');
1551     } else if (tui.mode.name == 'drop_thing' && event.key == 'Enter') {
1552         tui.pick_selectable('DROP');
1553     } else if (tui.mode.name == 'control_pw_pw' && event.key == 'Enter') {
1554         if (tui.inputEl.value.length == 0) {
1555             tui.log_msg('@ aborted');
1556         } else {
1557             server.send(['SET_MAP_CONTROL_PASSWORD',
1558                         tui.tile_control_char, tui.inputEl.value]);
1559             tui.log_msg('@ sent new password for protection character "' + tui.tile_control_char + '".');
1560         }
1561         tui.switch_mode('admin');
1562     } else if (tui.mode.name == 'portal' && event.key == 'Enter') {
1563         explorer.set_portal(tui.inputEl.value);
1564         tui.switch_mode('edit');
1565     } else if (tui.mode.name == 'name_thing' && event.key == 'Enter') {
1566         if (tui.inputEl.value.length == 0) {
1567             tui.inputEl.value = " ";
1568         }
1569         server.send(["THING_NAME", tui.selected_thing_id, tui.inputEl.value,
1570                      tui.password]);
1571         tui.switch_mode('edit');
1572     } else if (tui.mode.name == 'annotate' && event.key == 'Enter') {
1573         explorer.annotate(tui.inputEl.value);
1574         tui.switch_mode('edit');
1575     } else if (tui.mode.name == 'password' && event.key == 'Enter') {
1576         if (tui.inputEl.value.length == 0) {
1577             tui.inputEl.value = " ";
1578         }
1579         tui.password = tui.inputEl.value
1580         tui.switch_mode('edit');
1581     } else if (tui.mode.name == 'admin_enter' && event.key == 'Enter') {
1582         server.send(['BECOME_ADMIN', tui.inputEl.value]);
1583         tui.switch_mode('play');
1584     } else if (tui.mode.name == 'control_pw_type' && event.key == 'Enter') {
1585         if (tui.inputEl.value.length != 1) {
1586             tui.log_msg('@ entered non-single-char, therefore aborted');
1587             tui.switch_mode('admin');
1588         } else {
1589             tui.tile_control_char = tui.inputEl.value[0];
1590             tui.switch_mode('control_pw_pw');
1591         }
1592     } else if (tui.mode.name == 'control_tile_type' && event.key == 'Enter') {
1593         if (tui.inputEl.value.length != 1) {
1594             tui.log_msg('@ entered non-single-char, therefore aborted');
1595             tui.switch_mode('admin');
1596         } else {
1597             tui.tile_control_char = tui.inputEl.value[0];
1598             tui.switch_mode('control_tile_draw');
1599         }
1600     } else if (tui.mode.name == 'admin_thing_protect' && event.key == 'Enter') {
1601         if (tui.inputEl.value.length != 1) {
1602             tui.log_msg('@ entered non-single-char, therefore aborted');
1603         } else {
1604             server.send(['THING_PROTECTION', tui.selected_thing_id, tui.inputEl.value])
1605             tui.log_msg('@ sent new protection character for thing');
1606         }
1607         tui.switch_mode('admin');
1608     } else if (tui.mode.name == 'chat' && event.key == 'Enter') {
1609         let tokens = parser.tokenize(tui.inputEl.value);
1610         if (tokens.length > 0 && tokens[0].length > 0) {
1611             if (tui.inputEl.value[0][0] == '/') {
1612                 if (tokens[0].slice(1) == 'nick') {
1613                     if (tokens.length > 1) {
1614                         server.send(['NICK', tokens[1]]);
1615                     } else {
1616                         tui.log_msg('? need new name');
1617                     }
1618                 } else {
1619                     tui.log_msg('? unknown command');
1620                 }
1621             } else {
1622                     server.send(['ALL', tui.inputEl.value]);
1623             }
1624         } else if (tui.inputEl.valuelength > 0) {
1625                 server.send(['ALL', tui.inputEl.value]);
1626         }
1627         tui.inputEl.value = "";
1628     } else if (tui.mode.name == 'play') {
1629           if (tui.mode.mode_switch_on_key(event)) {
1630               null;
1631           } else if (event.key === tui.keys.consume && tui.task_action_on('consume')) {
1632               server.send(["TASK:INTOXICATE"]);
1633           } else if (event.key === tui.keys.door && tui.task_action_on('door')) {
1634               server.send(["TASK:DOOR"]);
1635           } else if (event.key === tui.keys.wear && tui.task_action_on('wear')) {
1636               server.send(["TASK:WEAR"]);
1637           } else if (event.key === tui.keys.spin && tui.task_action_on('spin')) {
1638               server.send(["TASK:SPIN"]);
1639           } else if (event.key in tui.movement_keys && tui.task_action_on('move')) {
1640               server.send(['TASK:MOVE', tui.movement_keys[event.key]]);
1641           } else if (event.key === tui.keys.teleport) {
1642               game.teleport();
1643           };
1644     } else if (tui.mode.name == 'study') {
1645         if (tui.mode.mode_switch_on_key(event)) {
1646               null;
1647         } else if (event.key in tui.movement_keys) {
1648             explorer.move(tui.movement_keys[event.key]);
1649         } else if (event.key == tui.keys.toggle_map_mode) {
1650             tui.toggle_map_mode();
1651         };
1652     } else if (tui.mode.name == 'control_tile_draw') {
1653         if (tui.mode.mode_switch_on_key(event)) {
1654             null;
1655         } else if (event.key in tui.movement_keys) {
1656             explorer.move(tui.movement_keys[event.key]);
1657         } else if (event.key === tui.keys.toggle_tile_draw) {
1658             tui.toggle_tile_draw();
1659         };
1660     } else if (tui.mode.name == 'admin') {
1661         if (tui.mode.mode_switch_on_key(event)) {
1662               null;
1663         } else if (event.key in tui.movement_keys && tui.task_action_on('move')) {
1664             server.send(['TASK:MOVE', tui.movement_keys[event.key]]);
1665         };
1666     } else if (tui.mode.name == 'edit') {
1667         if (tui.mode.mode_switch_on_key(event)) {
1668               null;
1669         } else if (event.key in tui.movement_keys && tui.task_action_on('move')) {
1670             server.send(['TASK:MOVE', tui.movement_keys[event.key]]);
1671         } else if (event.key === tui.keys.flatten && tui.task_action_on('flatten')) {
1672             server.send(["TASK:FLATTEN_SURROUNDINGS", tui.password]);
1673           } else if (event.key === tui.keys.install && tui.task_action_on('install')) {
1674               server.send(["TASK:INSTALL", tui.password]);
1675         } else if (event.key == tui.keys.toggle_map_mode) {
1676             tui.toggle_map_mode();
1677         }
1678     }
1679     tui.full_refresh();
1680 }, false);
1681
1682 rows_selector.addEventListener('input', function() {
1683     if (rows_selector.value % 4 != 0 || rows_selector.value < 24) {
1684         return;
1685     }
1686     window.localStorage.setItem(rows_selector.id, rows_selector.value);
1687     terminal.initialize();
1688     tui.full_refresh();
1689 }, false);
1690 cols_selector.addEventListener('input', function() {
1691     if (cols_selector.value % 4 != 0 || cols_selector.value < 80) {
1692         return;
1693     }
1694     window.localStorage.setItem(cols_selector.id, cols_selector.value);
1695     terminal.initialize();
1696     tui.window_width = terminal.cols / 2,
1697     tui.full_refresh();
1698 }, false);
1699 for (let key_selector of key_selectors) {
1700     key_selector.addEventListener('input', function() {
1701         window.localStorage.setItem(key_selector.id, key_selector.value);
1702         tui.init_keys();
1703     }, false);
1704 }
1705 window.setInterval(function() {
1706     if (server.websocket.readyState == 1) {
1707         server.send(['PING']);
1708     } else if (server.websocket.readyState != 0) {
1709         server.reconnect_to(server.url);
1710         tui.log_msg('@ attempting reconnect …')
1711     }
1712 }, 1000);
1713 window.setInterval(function() {
1714     if (document.activeElement.tagName.toLowerCase() != 'input') {
1715         const scroll_x = window.scrollX;
1716         const scroll_y = window.scrollY;
1717         tui.inputEl.focus();
1718         window.scrollTo(scroll_x, scroll_y);
1719     };
1720 }, 100);
1721 document.getElementById("help").onclick = function() {
1722     tui.show_help = true;
1723     tui.full_refresh();
1724 };
1725 for (const switchEl  of document.querySelectorAll('[id^="switch_to_"]')) {
1726     const mode = switchEl.id.slice("switch_to_".length);
1727     switchEl.onclick = function() {
1728         tui.switch_mode(mode);
1729         tui.full_refresh();
1730     }
1731 };
1732 document.getElementById("toggle_tile_draw").onclick = function() {
1733     tui.toggle_tile_draw();
1734 }
1735 document.getElementById("toggle_map_mode").onclick = function() {
1736     tui.toggle_map_mode();
1737     tui.full_refresh();
1738 };
1739 document.getElementById("flatten").onclick = function() {
1740     server.send(['TASK:FLATTEN_SURROUNDINGS', tui.password]);
1741 };
1742 document.getElementById("door").onclick = function() {
1743     server.send(['TASK:DOOR']);
1744 };
1745 document.getElementById("consume").onclick = function() {
1746     server.send(['TASK:INTOXICATE']);
1747 };
1748 document.getElementById("install").onclick = function() {
1749     server.send(['TASK:INSTALL']);
1750 };
1751 document.getElementById("wear").onclick = function() {
1752     server.send(['TASK:WEAR']);
1753 };
1754 document.getElementById("spin").onclick = function() {
1755     server.send(['TASK:SPIN']);
1756 };
1757 document.getElementById("teleport").onclick = function() {
1758     game.teleport();
1759 };
1760 for (const move_button of document.querySelectorAll('[id*="_move_"]')) {
1761     if (move_button.id.startsWith('key_')) {  // not a move button
1762         continue;
1763     };
1764     let direction = move_button.id.split('_')[2].toUpperCase();
1765     let move_repeat;
1766     move_button.onmousedown = function() {
1767         move_repeat = window.setInterval(function() {
1768             if (tui.mode.available_actions.includes("move")) {
1769                 server.send(['TASK:MOVE', direction]);
1770             } else if (tui.mode.available_actions.includes("move_explorer")) {
1771                 explorer.move(direction);
1772                 tui.full_refresh();
1773             };
1774         }, 100);
1775     };
1776     move_button.onmouseup = function() {
1777         window.clearInterval(move_repeat);
1778     }
1779 };
1780 </script>
1781 </body></html>