home · contact · privacy
Send game messages on player logins/renames.
[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         this.websocket.onclose = function(event) {
139             tui.log_msg('@ server disconnected :(');
140         }
141     },
142     send: function(tokens) {
143         this.websocket.send(unparser.untokenize(tokens));
144     }
145 }
146
147 let unparser = {
148     quote: function(str) {
149         let quoted = ['"'];
150         for (let i = 0; i < str.length; i++) {
151             let c = str[i];
152             if (c in ['"', '\\']) {
153                 quoted.push('\\');
154             };
155             quoted.push(c);
156         }
157         quoted.push('"');
158         return quoted.join('');
159     },
160     to_yx: function(yx_coordinate) {
161         return "Y:" + yx_coordinate[0] + ",X:" + yx_coordinate[1];
162     },
163     untokenize: function(tokens) {
164         let quoted_tokens = [];
165         for (let token of tokens) {
166             quoted_tokens.push(this.quote(token));
167         }
168         return quoted_tokens.join(" ");
169     }
170 }
171
172 class Mode {
173     constructor(name, has_input_prompt=false, shows_annotations=false, is_intro=false) {
174         this.name = name;
175         this.has_input_prompt = has_input_prompt;
176         this.shows_annotations = shows_annotations;
177         this.is_intro = is_intro;
178     }
179 }
180 let mode_waiting_for_server = new Mode('waiting_for_server', false, false, true);
181 let mode_login = new Mode('login', true, false, true);
182 let mode_chat = new Mode('chat / write messages to players', true, false);
183 let mode_annotate = new Mode('add message to map tile', true, true);
184 let mode_play = new Mode('play / move around', false, false);
185 let mode_study = new Mode('check map tiles for messages', false, true);
186 let mode_edit = new Mode('write ASCII char to map tile', false, false);
187
188 let tui = {
189   mode: mode_waiting_for_server,
190   log: [],
191   input_prompt: '> ',
192   input: '',
193   input_lines: [],
194   window_width: terminal.cols / 2,
195   height_turn_line: 1,
196   height_mode_line: 1,
197   height_input: 1,
198   key_up: 'w',
199   key_down: 's',
200   key_left: 'a',
201   key_right: 'd',
202   movement_keys_desc: 'w, a, s, d',
203   init: function() {
204       this.recalc_input_lines();
205       this.height_header = this.height_turn_line + this.height_mode_line;
206       this.log_msg("@ waiting for server connection ...");
207   },
208   init_login: function() {
209       this.log_msg("@ please enter your username:");
210       this.switch_mode(mode_login);
211   },
212   switch_mode: function(mode, keep_pos=false) {
213     if (mode == mode_study && !keep_pos) {
214       explorer.position = game.things[game.player_id];
215     }
216     this.mode = mode;
217     this.empty_input();
218     if (mode == mode_annotate && explorer.position in explorer.info_db) {
219         let info = explorer.info_db[explorer.position];
220         if (info != "(none)") {
221             this.add_to_input(explorer.info_db[explorer.position]);
222         }
223     }
224     this.full_refresh();
225   },
226   empty_input: function(str) {
227       this.input = "";
228       if (this.mode.has_input_prompt) {
229           this.recalc_input_lines();
230       } else {
231           this.height_input = 0;
232       }
233   },
234   add_to_input: function(str) {
235       if (this.input_prompt.length + this.input.length + str.length > this.window_width * terminal.rows) {
236           return;
237       }
238       this.input += str;
239       this.recalc_input_lines();
240       this.full_refresh();
241   },
242   recalc_input_lines: function() {
243       this.input_lines = this.msg_into_lines_of_width(this.input_prompt + this.input, this.window_width);
244       this.height_input = this.input_lines.length;
245   },
246   shorten_input: function() {
247       if (this.input.length == 0) {
248           terminal.blink_screen();
249       } else {
250           this.input = tui.input.slice(0, -1);
251           this.recalc_input_lines();
252           this.full_refresh();
253       }
254   },
255   msg_into_lines_of_width: function(msg, width) {
256     let chunk = "";
257     let lines = [];
258     for (let i = 0, x = 0; i < msg.length; i++, x++) {
259       if (x >= width) {
260         lines.push(chunk);
261         chunk = "";
262         x = 0;
263       };
264       chunk += msg[i];
265     }
266     lines.push(chunk);
267     return lines;
268   },
269   log_msg: function(msg) {
270       this.log.push(msg);
271       while (this.log.length > terminal.rows * 4) {
272         this.log.shift();
273       };
274       this.full_refresh();
275   },
276   log_help: function() {
277     this.log_msg("HELP:");
278     this.log_msg("chat mode commands:");
279     this.log_msg("  :nick NAME - re-name yourself to NAME");
280     this.log_msg("  :msg USER TEXT - send TEXT to USER");
281     this.log_msg("  :help - show this help");
282     this.log_msg("  :p or :play - switch to play mode");
283     this.log_msg("  :? or :study - switch to study mode");
284     this.log_msg("commands common to study and play mode:");
285     this.log_msg("  " + this.movement_keys_desc + " - move");
286     this.log_msg("  c - switch to chat mode");
287     this.log_msg("commands specific to play mode:");
288     this.log_msg("  e - write following ASCII character");
289     this.log_msg("  f - flatten surroundings");
290     this.log_msg("  ? - switch to study mode");
291     this.log_msg("commands specific to study mode:");
292     this.log_msg("  e - annotate terrain");
293     this.log_msg("  p - switch to play mode");
294   },
295   draw_map: function() {
296     let map_lines = [];
297     let line = [];
298     for (let i = 0, j = 0; i < game.map.length; i++, j++) {
299         if (j == game.map_size[1]) {
300             map_lines.push(line);
301             line = [];
302             j = 0;
303         };
304         line.push(game.map[i]);
305     };
306     map_lines.push(line);
307     let player_position = [0,0];
308     let center_pos = [Math.floor(game.map_size[0] / 2),
309                       Math.floor(game.map_size[1] / 2)];
310     for (const thing_id in game.things) {
311         let t = game.things[thing_id];
312         map_lines[t[0]][t[1]] = '@';
313         if (game.player_id == thing_id) {
314             center_pos = t;
315         }
316     };
317     if (tui.mode.shows_annotations) {
318         map_lines[explorer.position[0]][explorer.position[1]] = '?';
319         center_pos = explorer.position;
320     }
321     let offset = [(terminal.rows / 2) - center_pos[0],
322                   this.window_width / 2 - center_pos[1]];
323       for (let term_y = offset[0], map_y = 0;
324            term_y < terminal.rows && map_y < game.map_size[0];
325            term_y++, map_y++) {
326         if (term_y >= 0) {
327             let to_draw = map_lines[map_y].join('').slice(0, this.window_width - offset[1]);
328             terminal.write(term_y, offset[1], to_draw);
329         }
330     }
331   },
332   draw_mode_line: function() {
333       terminal.write(0, this.window_width, 'MODE: ' + this.mode.name);
334   },
335   draw_turn_line: function(n) {
336     terminal.write(1, this.window_width, 'TURN: ' + game.turn);
337   },
338   draw_history: function() {
339       let log_display_lines = [];
340       for (let line of this.log) {
341           log_display_lines = log_display_lines.concat(this.msg_into_lines_of_width(line, this.window_width));
342       };
343       for (let y = terminal.rows - 1 - this.height_input,
344                i = log_display_lines.length - 1;
345            y >= this.height_header && i >= 0;
346            y--, i--) {
347           terminal.write(y, this.window_width, log_display_lines[i]);
348       }
349   },
350   draw_info: function() {
351     let lines = this.msg_into_lines_of_width(explorer.get_info(), this.window_width);
352     for (let y = this.height_header, i = 0; y < terminal.rows && i < lines.length; y++, i++) {
353       terminal.write(y, this.window_width, lines[i]);
354     }
355   },
356   draw_input: function() {
357     if (this.mode.has_input_prompt) {
358         for (let y = terminal.rows - this.height_input, i = 0; y < terminal.rows && i < this.input_lines.length; y++, i++) {
359             terminal.write(y, this.window_width, this.input_lines[i]);
360         }
361     }
362   },
363   full_refresh: function() {
364     terminal.drawBox(0, 0, terminal.rows, terminal.cols);
365     if (this.mode.is_intro) {
366         this.draw_history();
367         this.draw_input();
368     } else {
369         this.draw_map();
370         this.draw_turn_line();
371         this.draw_mode_line();
372         if (this.mode.shows_annotations) {
373           this.draw_info();
374         } else {
375           this.draw_history();
376         }
377         this.draw_input();
378     }
379     terminal.refresh();
380   }
381 }
382
383 let game = {
384   things: {},
385   turn: 0,
386   map: "",
387   map_size: [0,0],
388   player_id: 0
389 }
390
391 terminal.initialize();
392 tui.init();
393 tui.full_refresh();
394
395 server.init(websocket_location);
396 server.websocket.onmessage = function (event) {
397   let tokens = parser.tokenize(event.data)[0];
398   if (tokens[0] === 'TURN') {
399     game.things = {}
400     game.turn = parseInt(tokens[1]);
401   } else if (tokens[0] === 'THING_POS') {
402     game.things[tokens[1]] = parser.parse_yx(tokens[2]);
403   } else if (tokens[0] === 'MAP') {
404     game.map_size = parser.parse_yx(tokens[1]);
405     game.map = tokens[2]
406   } else if (tokens[0] === 'GAME_STATE_COMPLETE') {
407     explorer.empty_info_db();
408     if (tui.mode == mode_study) {
409       explorer.query_info();
410     }
411     tui.full_refresh();
412   } else if (tokens[0] === 'CHAT') {
413      tui.log_msg('# ' + tokens[1], 1);
414   } else if (tokens[0] === 'PLAYER_ID') {
415       game.player_id = parseInt(tokens[1]);
416   } else if (tokens[0] === 'LOGIN_OK') {
417       server.send(['GET_GAMESTATE']);
418       tui.log_msg('@ ' + tokens[1]);
419       tui.log_help();
420       tui.switch_mode(mode_play);
421   } else if (tokens[0] === 'ANNOTATION') {
422      let position = parser.parse_yx(tokens[1]);
423      explorer.update_info_db(position, tokens[2]);
424   } else if (tokens[0] === 'UNHANDLED_INPUT') {
425      tui.log_msg('? unknown command');
426   } else if (tokens[0] === 'PLAY_ERROR') {
427      terminal.blink_screen();
428   } else if (tokens[0] === 'ARGUMENT_ERROR') {
429      tui.log_msg('? syntax error: ' + tokens[1]);
430   } else if (tokens[0] === 'GAME_ERROR') {
431      tui.log_msg('? game error: ' + tokens[1]);
432   } else if (tokens[0] === 'PONG') {
433     console.log('PONG');
434   } else {
435      tui.log_msg('? unhandled input: ' + event.data);
436   }
437 }
438
439 let explorer = {
440     position: [0,0],
441     info_db: {},
442     move: function(direction) {
443         let try_pos = [0,0];
444         try_pos[0] = this.position[0];
445         try_pos[1] = this.position[1];
446         if (direction == 'left') {
447             try_pos[1] -= 1;
448         } else if (direction == 'right') {
449             try_pos[1] += 1;
450         } else if (direction == 'up') {
451             try_pos[0] -= 1;
452         } else if (direction == 'down') {
453             try_pos[0] += 1;
454         };
455         if (!(try_pos[0] < 0) &&
456             !(try_pos[1] < 0) &&
457             !(try_pos[0] >= game.map_size[0])
458             && !(try_pos[1] >= game.map_size[1])) {
459             this.position = try_pos;
460             this.query_info();
461             tui.full_refresh();
462         }
463     },
464     update_info_db: function(yx, str) {
465         this.info_db[yx] = str;
466         if (tui.mode == mode_study) {
467             tui.full_refresh();
468         }
469     },
470     empty_info_db: function() {
471         this.info_db = {};
472         if (tui.mode == mode_study) {
473             tui.full_refresh();
474         }
475     },
476     query_info: function() {
477         server.send(["GET_ANNOTATION", unparser.to_yx(explorer.position)]);
478     },
479     get_info: function() {
480         if (this.position in this.info_db) {
481             return this.info_db[this.position];
482         } else {
483             return 'waiting …';
484         }
485     },
486     annotate: function(msg) {
487         if (msg.length == 0) {
488             msg = " ";  // triggers annotation deletion
489         }
490         server.send(["ANNOTATE", unparser.to_yx(explorer.position), msg]);
491     }
492 }
493
494 document.addEventListener('keydown', (event) => {
495     if (tui.mode.has_input_prompt && event.key.length === 1) {
496         tui.add_to_input(event.key);
497     } else if (tui.mode.has_input_prompt && event.key == 'Backspace') {
498         tui.shorten_input();
499     } else if (tui.mode == mode_login && event.key == 'Enter') {
500         server.send(['LOGIN', tui.input]);
501         tui.switch_mode(mode_login);
502     } else if (tui.mode == mode_annotate && event.key == 'Enter') {
503         explorer.annotate(tui.input);
504         tui.switch_mode(mode_study, true);
505     } else if (tui.mode == mode_chat && event.key == 'Enter') {
506         let [tokens, token_starts] = parser.tokenize(tui.input);
507         if (tokens.length > 0 && tokens[0].length > 0) {
508             if (tokens[0][0] == ':') {
509                 if (tokens[0] == ':play' || tokens[0] == ':p') {
510                     tui.switch_mode(mode_play);
511                 } else if (tokens[0] == ':study' || tokens[0] == ':?') {
512                     tui.switch_mode(mode_study);
513                 } else if (tokens[0] == ':help') {
514                     tui.log_help();
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           } else if (event.key === 'f') {
547               server.send(["TASK:FLATTEN_SURROUNDINGS"]);
548           } else if (event.key === tui.key_left) {
549               server.send(['TASK:MOVE', 'LEFT']);
550           } else if (event.key === tui.key_right) {
551               server.send(['TASK:MOVE', 'RIGHT']);
552           } else if (event.key === tui.key_up) {
553               server.send(['TASK:MOVE', 'UP']);
554           } else if (event.key === tui.key_down) {
555               server.send(['TASK:MOVE', 'DOWN']);
556           };
557     } else if (tui.mode == mode_edit) {
558         if (event.key != "Shift" && event.key.length == 1) {
559             server.send(["TASK:WRITE", event.key]);
560             tui.switch_mode(mode_play);
561         }
562     } else if (tui.mode == mode_study) {
563         if (event.key === 'c') {
564             tui.switch_mode(mode_chat);
565         } else if (event.key == 'p') {
566             tui.switch_mode(mode_play);
567         } else if (event.key === tui.key_left) {
568               explorer.move('left');
569         } else if (event.key === tui.key_right) {
570               explorer.move('right');
571         } else if (event.key === tui.key_up) {
572               explorer.move('up');
573         } else if (event.key === tui.key_down) {
574               explorer.move('down');
575         } else if (event.key === 'e') {
576           tui.switch_mode(mode_annotate);
577         };
578     }
579 }, false);
580
581 let wasd_selector = document.getElementById("WASD_selector");
582 wasd_selector.addEventListener('input', function() {
583     if (wasd_selector.value == 'w, a, s, d') {
584         tui.key_up = 'w';
585         tui.key_down = 's';
586         tui.key_left = 'a';
587         tui.key_right = 'd';
588     } else if (wasd_selector.value == 'arrow keys') {
589         tui.key_up = 'ArrowUp';
590         tui.key_down = 'ArrowDown';
591         tui.key_left = 'ArrowLeft';
592         tui.key_right = 'ArrowRight';
593     };
594     tui.movement_keys_desc = wasd_selector.value;
595 }, false);
596 let rows_selector = document.getElementById("n_rows");
597 rows_selector.addEventListener('input', function() {
598     terminal.rows = rows_selector.value;
599     terminal.initialize();
600     tui.full_refresh();
601 }, false);
602 let cols_selector = document.getElementById("n_cols");
603 cols_selector.addEventListener('input', function() {
604     terminal.cols = cols_selector.value;
605     terminal.initialize();
606     tui.window_width = terminal.cols / 2,
607     tui.full_refresh();
608 }, false);
609 </script>
610 </body></html>