frontend.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { GameOptions } from './game/objects';
  2. import { MainDisplayController } from './display/engine';
  3. import { GameWorld } from './backend/types';
  4. import { BackendClient, RequestMetod } from './backend/api-helper';
  5. import { EliasDBGraphQLClient } from './backend/eliasdb-graphql';
  6. import { MainGameController } from './game/game-controller';
  7. import { generateRandomName, getURLParams, setURLParam } from './helper';
  8. export default {
  9. start: async function (canvasId: string) {
  10. // Initial values
  11. const host = `${window.location.hostname}:${window.location.port}`;
  12. const gameName = 'main';
  13. // Create backend client to send game specific requests
  14. const bc = new BackendClient(host, gameName);
  15. // Get option details
  16. const options = new GameOptions();
  17. try {
  18. let res = await bc.req(
  19. '/game',
  20. {
  21. gameName
  22. },
  23. RequestMetod.Get
  24. );
  25. const gm = res.gameworld as GameWorld;
  26. // Set game world related options
  27. options.backdrop = null; // TODO Asset load: gm.backdrop
  28. options.screenWidth = gm.screenWidth;
  29. options.screenHeight = gm.screenHeight;
  30. options.screenElementWidth = gm.screenElementWidth;
  31. options.screenElementHeight = gm.screenElementHeight;
  32. } catch (e) {
  33. throw new Error(`Could not register: ${e}`);
  34. }
  35. const ec = new EliasDBGraphQLClient(host, gameName);
  36. const mdc = new MainDisplayController(canvasId, options);
  37. // TODO: Register the player and let the game controller subscribe to the state
  38. let params = getURLParams();
  39. if (!params.player) {
  40. setURLParam('player', generateRandomName());
  41. params = getURLParams();
  42. }
  43. const playerName = params.player;
  44. try {
  45. await bc.req('/player', {
  46. player: playerName,
  47. gameName
  48. });
  49. const gc = new MainGameController(
  50. gameName,
  51. playerName,
  52. mdc,
  53. bc,
  54. ec
  55. );
  56. await gc.start();
  57. } catch (e) {
  58. throw new Error(`Could not register: ${e}`);
  59. }
  60. }
  61. };