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