BranchingOptions.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /// <reference path="../../../Functions.ts" />
  2. class BranchingOption {
  3. public say : Say;
  4. public appearCondition : (() => boolean) | boolean;
  5. public previouslyPicked : boolean = false;
  6. public constructor (say : Say, appearCondition? : (() => boolean) | boolean) {
  7. this.say = say;
  8. this.appearCondition = appearCondition;
  9. }
  10. }
  11. class BranchingDialogue {
  12. private options : Array<BranchingOption> = [];
  13. private resolve : Function;
  14. public constructor (...options : Array<BranchingOption>) {
  15. this.addOptions(...options);
  16. }
  17. public addOptions (...options : Array<BranchingOption>) {
  18. this.options.push(...options);
  19. arrayUnique(this.options);
  20. }
  21. public async getChosenOption () : Promise<BranchingOption> {
  22. let validOptions = [];
  23. for (let i = 0, value = this.options[i]; value != undefined; value = this.options[++i]) {
  24. if (value.appearCondition == undefined || (typeof value.appearCondition == "function" && value.appearCondition()) || value.appearCondition) {
  25. validOptions.push(value);
  26. }
  27. }
  28. let choiceButtons : Array<HTMLElement> = [];
  29. for (let i = 0; i < validOptions.length; i++) {
  30. let value = validOptions[i];
  31. let classes = ["choice"];
  32. if (value.previouslyPicked) {
  33. classes.push("picked");
  34. }
  35. choiceButtons.push((await value.say.getHTML("p", classes))[0]);
  36. }
  37. let PlayerInput : Promise<BranchingOption> = new Promise((resolve, reject) => {
  38. this.resolve = resolve;
  39. });
  40. Controls.KeyHandler.reset();
  41. for (let index = 0, value = choiceButtons[index]; value != undefined; value = choiceButtons[++index]) {
  42. Controls.KeyHandler.applyCode(value, Controls.KeyHandler.getFirstKeyCode());
  43. value.addEventListener("click", (e) => {
  44. validOptions[index].previouslyPicked = true;
  45. this.resolve(validOptions[index]);
  46. e.preventDefault();
  47. });
  48. }
  49. await Elements.CurrentTurnHandler.print(...choiceButtons);
  50. let choice = await PlayerInput;
  51. await Elements.CurrentTurnHandler.unprint(...choiceButtons);
  52. return choice;
  53. }
  54. }