app.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /// <reference path="player.ts" />
  2. function startGame() {
  3. // Starting a new game.
  4. let playerName: string | undefined = getInputValue('playername');
  5. logPlayer(playerName);
  6. postScore(100, playerName);
  7. }
  8. function getInputValue(elementId: string): string | undefined {
  9. // Type assertions applies to the whole document.get...., not to document.
  10. // We know that we're only going to pass valid IDs, so will never get a null,
  11. // so we can assert the result will always be an input element.
  12. const inputElement: HTMLInputElement = <HTMLInputElement>document.getElementById(elementId);
  13. if (inputElement.value === '') {
  14. return undefined;
  15. }
  16. else {
  17. return inputElement.value;
  18. }
  19. }
  20. function postScore(score: number, playerName: string = 'MultiMath player'): void {
  21. let logger: (value: string) => void;
  22. if (score < 0) {
  23. logger = logError;
  24. }
  25. else {
  26. logger = logMessage;
  27. }
  28. let scoreElement: HTMLElement | null = document.getElementById('postedScores');
  29. scoreElement!.innerText = `${score} - ${playerName}`;
  30. logger(`Score: ${score}`);
  31. }
  32. function logPlayer(name: string = 'MultiMath player'): void {
  33. console.log(`New game starting for player: ${name}.`);
  34. }
  35. function arm(doc: HTMLDocument) {
  36. // We know getElementById() cannot be null because we control the markup, so
  37. // we can use a non-null type assertion on the function call result.
  38. doc.getElementById('startGame')!.addEventListener('click', startGame);
  39. }
  40. arm(document);
  41. const logMessage = (message: string) => console.log(message);
  42. function logError(message: string): void {
  43. console.error(message);
  44. }
  45. let firstPlayer: Player = new Player();
  46. firstPlayer.name = 'Laney';
  47. console.log(firstPlayer.formatName());