home · contact · privacy
Refactor movement selector, add terminal height/width selectors.
[plomrogue2-experiments] / new2 / rogue_chat_nocanvas_monochrome.html
1 <!DOCTYPE html>
2 <html><head>
3 <style>
4 </style>
5 </head><body>
6 <div>
7 movement: <select id="WASD_selector" name="WASD_selector" >
8 <option value="w, a, s, d" selected>w, a, s, d</option>
9 <option value="arrow keys">arrow keys</option>
10 </select>
11 rows: <input id="n_rows" type="number" step=2 min=10 value=24 />
12 cols: <input id="n_cols" type="number" step=4 min=20 value=80 />
13 </div>
14 <pre id="terminal" style="display: inline-block;"></pre>
15 <script>
16 "use strict";
17 let websocket_location = "ws://localhost:8000";
18
19 let terminal = {
20   rows: 24,
21   cols: 80,
22   foreground: 'white',
23   background: 'black',
24   initialize: function() {
25     this.pre_el = document.getElementById("terminal");
26     this.pre_el.style.color = this.foreground;
27     this.pre_el.style.backgroundColor = this.background;
28     this.content = [];
29       let line = []
30     for (let y = 0, x = 0; y <= this.rows; x++) {
31         if (x == this.cols) {
32             x = 0;
33             y += 1;
34             this.content.push(line);
35             line = [];
36             if (y == this.rows) {
37                 break;
38             }
39         }
40         line.push(' ');
41     }
42   },
43   blink_screen: function() {
44       this.pre_el.style.color = this.background;
45       this.pre_el.style.backgroundColor = this.foreground;
46       setTimeout(() => {
47           this.pre_el.style.color = this.foreground;
48           this.pre_el.style.backgroundColor = this.background;
49       }, 100);
50   },
51   refresh: function() {
52       let pre_string = '';
53       for (let y = 0; y < this.rows; y++) {
54           let line = this.content[y].join('');
55           pre_string += line + '\n';
56       }
57       this.pre_el.textContent = pre_string;
58   },
59   write: function(start_y, start_x, msg) {
60       for (let x = start_x, i = 0; x < this.cols && i < msg.length; x++, i++) {
61           this.content[start_y][x] = msg[i];
62       }
63   },
64   drawBox: function(start_y, start_x, height, width) {
65     let end_y = start_y + height;
66     let end_x = start_x + width;
67     for (let y = start_y, x = start_x; y < this.rows; x++) {
68       if (x == end_x) {
69         x = start_x;
70         y += 1;
71         if (y == end_y) {
72             break;
73         }
74       };
75       this.content[y][x] = ' ';
76     }
77   },
78 }
79
80 let parser = {
81   tokenize: function(str) {
82     let token_ends = [];
83     let tokens = [];
84     let token = ''
85     let quoted = false;
86     let escaped = false;
87     for (let i = 0; i < str.length; i++) {
88       let c = str[i];
89       if (quoted) {
90         if (escaped) {
91           token += c;
92           escaped = false;
93         } else if (c == '\\') {
94           escaped = true;
95         } else if (c == '"') {
96           quoted = false
97         } else {
98           token += c;
99         }
100       } else if (c == '"') {
101         quoted = true
102       } else if (c === ' ') {
103         if (token.length > 0) {
104           token_ends.push(i);
105           tokens.push(token);
106           token = '';
107         }
108       } else {
109         token += c;
110       }
111     }
112     if (token.length > 0) {
113       tokens.push(token);
114     }
115     let token_starts = [];
116     for (let i = 0; i < token_ends.length; i++) {
117       token_starts.push(token_ends[i] - tokens[i].length);
118     };
119     return [tokens, token_starts];
120   },
121   parse_yx: function(position_string) {
122     let coordinate_strings = position_string.split(',')
123     let position = [0, 0];
124     position[0] = parseInt(coordinate_strings[0].slice(2));
125     position[1] = parseInt(coordinate_strings[1].slice(2));
126     return position;
127   },
128 }
129
130 let server = {
131     init: function(url) {
132         this.websocket = new WebSocket(url);
133         this.websocket.onopen = function(event) {
134             window.setInterval(function() { server.send(['PING']) }, 30000);
135             tui.log_msg("@ server connected!");
136             tui.init_login();
137         };
138     },
139     send: function(tokens) {
140         if (this.websocket.readyState !== WebSocket.OPEN) {
141             tui.log_msg('server disconnected :(');
142         } else {
143             this.websocket.send(unparser.untokenize(tokens));
144         }
145     }
146 }
147
148 let unparser = {
149     quote: function(str) {
150         let quoted = ['"'];
151         for (let i = 0; i < str.length; i++) {
152             let c = str[i];
153             if (c in ['"', '\\']) {
154                 quoted.push('\\');
155             };
156             quoted.push(c);
157         }
158         quoted.push('"');
159         return quoted.join('');
160     },
161     to_yx: function(yx_coordinate) {
162         return "Y:" + yx_coordinate[0] + ",X:" + yx_coordinate[1];
163     },
164     untokenize: function(tokens) {
165         let quoted_tokens = [];
166         for (let token of tokens) {
167             quoted_tokens.push(this.quote(token));
168         }
169         return quoted_tokens.join(" ");
170     }
171 }
172
173 class Mode {
174     constructor(name, has_input_prompt=false, shows_annotations=false, is_intro=false) {
175         this.name = name;
176         this.has_input_prompt = has_input_prompt;
177         this.shows_annotations = shows_annotations;
178         this.is_intro = is_intro;
179     }
180 }
181 let mode_waiting_for_server = new Mode('waiting_for_server', false, false, true);
182 let mode_login = new Mode('login', true, false, true);
183 let mode_chat = new Mode('chat / write messages to players', true, false);
184 let mode_annotate = new Mode('add message to map tile', true, true);
185 let mode_play = new Mode('play / move around', false, false);
186 let mode_study = new Mode('check map tiles for messages', false, true);
187 let mode_edit = new Mode('write ASCII char to map tile', false, false);
188
189 let tui = {
190   mode: mode_waiting_for_server,
191   log: [],
192   input_prompt: '> ',
193   input: '',
194   input_lines: [],
195   window_width: terminal.cols / 2,
196   height_turn_line: 1,
197   height_mode_line: 1,
198   height_input: 1,
199   key_up: 'w',
200   key_down: 's',
201   key_left: 'a',
202   key_right: 'd',
203   movement_keys_desc: 'w, a, s, d',
204   init: function() {
205       this.recalc_input_lines();
206       this.height_header = this.height_turn_line + this.height_mode_line;
207       this.log_msg("@ waiting for server connection ...");
208   },
209   init_login: function() {
210       this.log_msg("@ please enter your username:");
211       this.switch_mode(mode_login);
212   },
213   switch_mode: function(mode, keep_pos=false) {
214     if (mode == mode_study && !keep_pos) {
215       explorer.position = game.things[game.player_id];
216     }
217     this.mode = mode;
218     this.empty_input();
219     if (mode == mode_annotate && explorer.position in explorer.info_db) {
220         let info = explorer.info_db[explorer.position];
221         if (info != "(none)") {
222             this.add_to_input(explorer.info_db[explorer.position]);
223         }
224     }
225     this.full_refresh();
226   },
227   empty_input: function(str) {
228       this.input = "";
229       if (this.mode.has_input_prompt) {
230           this.recalc_input_lines();
231       } else {
232           this.height_input = 0;
233       }
234   },
235   add_to_input: function(str) {
236       if (this.input_prompt.length + this.input.length + str.length > this.window_width * terminal.rows) {
237           return;
238       }
239       this.input += str;
240       this.recalc_input_lines();
241       this.full_refresh();
242   },
243   recalc_input_lines: function() {
244       this.input_lines = this.msg_into_lines_of_width(this.input_prompt + this.input, this.window_width);
245       this.height_input = this.input_lines.length;
246   },
247   shorten_input: function() {
248       if (this.input.length == 0) {
249           terminal.blink_screen();
250       } else {
251           this.input = tui.input.slice(0, -1);
252           this.recalc_input_lines();
253           this.full_refresh();
254       }
255   },
256   msg_into_lines_of_width: function(msg, width) {
257     let chunk = "";
258     let lines = [];
259     for (let i = 0, x = 0; i < msg.length; i++, x++) {
260       if (x >= width) {
261         lines.push(chunk);
262         chunk = "";
263         x = 0;
264       };
265       chunk += msg[i];
266     }
267     lines.push(chunk);
268     return lines;
269   },
270   log_msg: function(msg) {
271       let lines = this.msg_into_lines_of_width(msg, this.window_width);
272       this.log = this.log.concat(lines);
273       while (this.log.length > terminal.rows) {
274         this.log.shift();
275       };
276       this.full_refresh();
277   },
278   log_help: function() {
279     this.log_msg("HELP:");
280     this.log_msg("chat mode commands:");
281     this.log_msg("  :nick NAME - re-name yourself to NAME");
282     this.log_msg("  :msg USER TEXT - send TEXT to USER");
283     this.log_msg("  :help - show this help");
284     this.log_msg("  :p or :play - switch to play mode");
285     this.log_msg("  :? or :study - switch to study mode");
286     this.log_msg("commands common to study and play mode:");
287     this.log_msg("  " + this.movement_keys_desc + " - move");
288     this.log_msg("  c - switch to chat mode");
289     this.log_msg("commands specific to play mode:");
290     this.log_msg("  e - write following ASCII character");
291     this.log_msg("  f - flatten surroundings");
292     this.log_msg("  ? - switch to study mode");
293     this.log_msg("commands specific to study mode:");
294     this.log_msg("  e - annotate terrain");
295     this.log_msg("  p - switch to play mode");
296   },
297   draw_map: function() {
298     let map_lines = [];
299     let line = [];
300     for (let i = 0, j = 0; i < game.map.length; i++, j++) {
301         if (j == game.map_size[1]) {
302             map_lines.push(line);
303             line = [];
304             j = 0;
305         };
306         line.push(game.map[i]);
307     };
308     map_lines.push(line);
309     let player_position = [0,0];
310     let center_pos = [Math.floor(game.map_size[0] / 2),
311                       Math.floor(game.map_size[1] / 2)];
312     for (const thing_id in game.things) {
313         let t = game.things[thing_id];
314         map_lines[t[0]][t[1]] = '@';
315         if (game.player_id == thing_id) {
316             center_pos = t;
317         }
318     };
319     if (tui.mode.shows_annotations) {
320         map_lines[explorer.position[0]][explorer.position[1]] = '?';
321         center_pos = explorer.position;
322     }
323     let offset = [(terminal.rows / 2) - center_pos[0],
324                   this.window_width / 2 - center_pos[1]];
325       for (let term_y = offset[0], map_y = 0;
326            term_y < terminal.rows && map_y < game.map_size[0];
327            term_y++, map_y++) {
328         if (term_y >= 0) {
329             let to_draw = map_lines[map_y].join('').slice(0, this.window_width - offset[1]);
330             terminal.write(term_y, offset[1], to_draw);
331         }
332     }
333   },
334   draw_mode_line: function() {
335       terminal.write(0, this.window_width, 'MODE: ' + this.mode.name);
336   },
337   draw_turn_line: function(n) {
338     terminal.write(1, this.window_width, 'TURN: ' + game.turn);
339   },
340   draw_history: function() {
341     if (terminal.rows <= this.height_header + this.height_input) {
342         return;
343     }
344       for (let y = terminal.rows - 1 - this.height_input,
345                i = this.log.length - 1;
346            y >= this.height_header && i >= 0;
347            y--, i--) {
348           terminal.write(y, this.window_width, this.log[i]);
349       }
350   },
351   draw_info: function() {
352     let lines = this.msg_into_lines_of_width(explorer.get_info(), this.window_width);
353     for (let y = this.height_header, i = 0; y < terminal.rows && i < lines.length; y++, i++) {
354       terminal.write(y, this.window_width, lines[i]);
355     }
356   },
357   draw_input: function() {
358     if (this.mode.has_input_prompt) {
359         for (let y = terminal.rows - this.height_input, i = 0; y < terminal.rows && i < this.input_lines.length; y++, i++) {
360             terminal.write(y, this.window_width, this.input_lines[i]);
361         }
362     }
363   },
364   full_refresh: function() {
365     terminal.drawBox(0, 0, terminal.rows, terminal.cols);
366     if (this.mode.is_intro) {
367         this.draw_history();
368         this.draw_input();
369     } else {
370         this.draw_map();
371         this.draw_turn_line();
372         this.draw_mode_line();
373         if (this.mode.shows_annotations) {
374           this.draw_info();
375         } else {
376           this.draw_history();
377         }
378         this.draw_input();
379     }
380     terminal.refresh();
381   }
382 }
383
384 let game = {
385   things: {},
386   turn: 0,
387   map: "",
388   map_size: [0,0],
389   player_id: 0
390 }
391
392 terminal.initialize();
393 tui.init();
394 tui.full_refresh();
395
396 server.init(websocket_location);
397 server.websocket.onmessage = function (event) {
398   let tokens = parser.tokenize(event.data)[0];
399   if (tokens[0] === 'TURN') {
400     game.things = {}
401     game.turn = parseInt(tokens[1]);
402   } else if (tokens[0] === 'THING_POS') {
403     game.things[tokens[1]] = parser.parse_yx(tokens[2]);
404   } else if (tokens[0] === 'MAP') {
405     game.map_size = parser.parse_yx(tokens[1]);
406     game.map = tokens[2]
407   } else if (tokens[0] === 'GAME_STATE_COMPLETE') {
408     explorer.empty_info_db();
409     if (tui.mode == mode_study) {
410       explorer.query_info();
411     }
412     tui.full_refresh();
413   } else if (tokens[0] === 'CHAT') {
414      tui.log_msg('# ' + tokens[1], 1);
415   } else if (tokens[0] === 'PLAYER_ID') {
416       game.player_id = parseInt(tokens[1]);
417   } else if (tokens[0] === 'META') {
418      tui.log_msg('@ ' + tokens[1]);
419   } else if (tokens[0] === 'LOGIN_OK') {
420       server.send(['GET_GAMESTATE']);
421       tui.log_msg('@ ' + tokens[1]);
422       tui.log_help();
423       tui.switch_mode(mode_chat);
424   } else if (tokens[0] === 'ANNOTATION') {
425      let position = parser.parse_yx(tokens[1]);
426      explorer.update_info_db(position, tokens[2]);
427   } else if (tokens[0] === 'UNHANDLED_INPUT') {
428      tui.log_msg('? unknown command');
429   } else if (tokens[0] === 'PLAY_ERROR') {
430      terminal.blink_screen();
431   } else if (tokens[0] === 'ARGUMENT_ERROR') {
432      tui.log_msg('? syntax error: ' + tokens[1]);
433   } else if (tokens[0] === 'GAME_ERROR') {
434      tui.log_msg('? game error: ' + tokens[1]);
435   } else if (tokens[0] === 'PONG') {
436     console.log('PONG');
437   } else {
438      tui.log_msg('? unhandled input: ' + event.data);
439   }
440 }
441
442 let explorer = {
443     position: [0,0],
444     info_db: {},
445     move: function(direction) {
446         let try_pos = [0,0];
447         try_pos[0] = this.position[0];
448         try_pos[1] = this.position[1];
449         if (direction == 'left') {
450             try_pos[1] -= 1;
451         } else if (direction == 'right') {
452             try_pos[1] += 1;
453         } else if (direction == 'up') {
454             try_pos[0] -= 1;
455         } else if (direction == 'down') {
456             try_pos[0] += 1;
457         };
458         if (!(try_pos[0] < 0) &&
459             !(try_pos[1] < 0) &&
460             !(try_pos[0] >= game.map_size[0])
461             && !(try_pos[1] >= game.map_size[1])) {
462             this.position = try_pos;
463             this.query_info();
464             tui.full_refresh();
465         }
466     },
467     update_info_db: function(yx, str) {
468         this.info_db[yx] = str;
469         if (tui.mode == mode_study) {
470             tui.full_refresh();
471         }
472     },
473     empty_info_db: function() {
474         this.info_db = {};
475         if (tui.mode == mode_study) {
476             tui.full_refresh();
477         }
478     },
479     query_info: function() {
480         server.send(["GET_ANNOTATION", unparser.to_yx(explorer.position)]);
481     },
482     get_info: function() {
483         if (this.position in this.info_db) {
484             return this.info_db[this.position];
485         } else {
486             return 'waiting …';
487         }
488     },
489     annotate: function(msg) {
490         if (msg.length == 0) {
491             msg = " ";  // triggers annotation deletion
492         }
493         server.send(["ANNOTATE", unparser.to_yx(explorer.position), msg]);
494     }
495 }
496
497 document.addEventListener('keydown', (event) => {
498     if (tui.mode.has_input_prompt && event.key.length === 1) {
499         tui.add_to_input(event.key);
500     } else if (tui.mode.has_input_prompt && event.key == 'Backspace') {
501         tui.shorten_input();
502     } else if (tui.mode == mode_login && event.key == 'Enter') {
503         server.send(['LOGIN', tui.input]);
504         tui.switch_mode(mode_login);
505     } else if (tui.mode == mode_annotate && event.key == 'Enter') {
506         explorer.annotate(tui.input);
507         tui.switch_mode(mode_study, true);
508     } else if (tui.mode == mode_chat && event.key == 'Enter') {
509         let [tokens, token_starts] = parser.tokenize(tui.input);
510         if (tokens.length > 0 && tokens[0].length > 0) {
511             if (tokens[0][0] == ':') {
512                 if (tokens[0] == ':play' || tokens[0] == ':p') {
513                     tui.switch_mode(mode_play);
514                 } else if (tokens[0] == ':study' || tokens[0] == ':?') {
515                     tui.switch_mode(mode_study);
516                 } else if (tokens[0] == ':help') {
517                     tui.log_help();
518                 } else if (tokens[0] == ':nick') {
519                     if (tokens.length > 1) {
520                         server.send(['LOGIN', tokens[1]]);
521                     } else {
522                         tui.log_msg('? need login name');
523                     }
524                 } else if (tokens[0] == ':msg') {
525                     if (tokens.length > 2) {
526                         let msg = tui.input.slice(token_starts[2]);
527                         server.send(['QUERY', tokens[1], msg]);
528                     } else {
529                         tui.log_msg('? need message target and message');
530                     }
531                 } else {
532                     tui.log_msg('? unknown command');
533                 }
534             } else {
535                 server.send(['ALL', tui.input]);
536             }
537         }
538         tui.empty_input();
539         tui.full_refresh();
540       } else if (tui.mode == mode_play) {
541           if (event.key === 'c') {
542               tui.switch_mode(mode_chat);
543           } else if (event.key === 'e') {
544               tui.switch_mode(mode_edit);
545           } else if (event.key === '?') {
546               tui.switch_mode(mode_study);
547           } else if (event.key === 'F1') {
548               tui.log_help();
549           } else if (event.key === 'f') {
550               server.send(["TASK:FLATTEN_SURROUNDINGS"]);
551           } else if (event.key === tui.key_left) {
552               server.send(['TASK:MOVE', 'LEFT']);
553           } else if (event.key === tui.key_right) {
554               server.send(['TASK:MOVE', 'RIGHT']);
555           } else if (event.key === tui.key_up) {
556               server.send(['TASK:MOVE', 'UP']);
557           } else if (event.key === tui.key_down) {
558               server.send(['TASK:MOVE', 'DOWN']);
559           };
560     } else if (tui.mode == mode_edit) {
561         if (event.key != "Shift" && event.key.length == 1) {
562             server.send(["TASK:WRITE", event.key]);
563             tui.switch_mode(mode_play);
564         }
565     } else if (tui.mode == mode_study) {
566         if (event.key === 'c') {
567             tui.switch_mode(mode_chat);
568         } else if (event.key == 'p') {
569             tui.switch_mode(mode_play);
570         } else if (event.key === tui.key_left) {
571               explorer.move('left');
572         } else if (event.key === tui.key_right) {
573               explorer.move('right');
574         } else if (event.key === tui.key_up) {
575               explorer.move('up');
576         } else if (event.key === tui.key_down) {
577               explorer.move('down');
578         } else if (event.key === 'e') {
579           tui.switch_mode(mode_annotate);
580         };
581     }
582 }, false);
583
584 let wasd_selector = document.getElementById("WASD_selector");
585 wasd_selector.addEventListener('input', function() {
586     if (wasd_selector.value == 'w, a, s, d') {
587         tui.key_up = 'w';
588         tui.key_down = 's';
589         tui.key_left = 'a';
590         tui.key_right = 'd';
591     } else if (wasd_selector.value == 'arrow keys') {
592         tui.key_up = 'ArrowUp';
593         tui.key_down = 'ArrowDown';
594         tui.key_left = 'ArrowLeft';
595         tui.key_right = 'ArrowRight';
596     };
597     tui.movement_keys_desc = wasd_selector.value;
598 }, false);
599 let rows_selector = document.getElementById("n_rows");
600 rows_selector.addEventListener('input', function() {
601     terminal.rows = rows_selector.value;
602     terminal.initialize();
603     tui.full_refresh();
604 }, false);
605 let cols_selector = document.getElementById("n_cols");
606 cols_selector.addEventListener('input', function() {
607     terminal.cols = cols_selector.value;
608     terminal.initialize();
609     tui.window_width = terminal.cols / 2,
610     tui.full_refresh();
611 }, false);
612 </script>
613 </body></html>