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