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