game.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import {getValue} from "./utility";
  2. import {Player} from "./player";
  3. import {Result} from "./result";
  4. import {Scoreboard as ResultPanel} from "./scoreboard";
  5. export class Game {
  6. private scoreboard: ResultPanel = new ResultPanel();
  7. /**
  8. * Passing "public" parameters to constructor() automatically creates
  9. * properties of the same name and initializes them to the value of the passed
  10. * argument. Same with "protected", "private", and "readonly".
  11. *
  12. * The name for this is "parameter properties".
  13. *
  14. * @param player
  15. * @param problemCount
  16. * @param factor
  17. */
  18. constructor(
  19. public player: Player,
  20. public problemCount: number,
  21. public factor: number) {
  22. }
  23. displayGame(): void {
  24. // Create the HTML for the current game.
  25. let gameForm: string = '';
  26. for (let i = 1; i <= this.problemCount; i++) {
  27. gameForm += '<div class="form-group">';
  28. gameForm += '<label for="answer' + i + '" class="col-sm-2 control-label">';
  29. // Note use of the String constructor vs a type assertion: they do not
  30. // fulfill the same purpose.
  31. gameForm += String(this.factor) + ' x ' + i + ' = </label>';
  32. gameForm += '<div class="col-sm-1"><input type="text" class="form-control" id="answer' + i + '"></div>';
  33. gameForm += '</div>';
  34. }
  35. // Add the game to the page.
  36. let gameElement: HTMLElement = document.getElementById('game')!;
  37. gameElement.innerHTML = gameForm;
  38. // Enable the calculate score button.
  39. document.getElementById('calculate')!.removeAttribute('disabled');
  40. }
  41. calculateScore(): void {
  42. let score: number = 0;
  43. // Loop through the text boxes and calculate the number that are correct.
  44. for (let i = 1; i < this.problemCount; i++) {
  45. let answer: number = Number(getValue('answer' + i));
  46. if (i * this.factor === answer) {
  47. score++;
  48. }
  49. }
  50. // Create a new result object to pass to the scoreboard.
  51. let result: Result = {
  52. playerName: this.player.name,
  53. score,
  54. problemCount: this.problemCount,
  55. factor: this.factor,
  56. };
  57. this.scoreboard.addResult(result);
  58. this.scoreboard.updateScoreboard();
  59. // Disable the calculate score button.
  60. document.getElementById('calculate')!.setAttribute('disabled', 'true');
  61. }
  62. }