Game.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { GameState } from "./states/GameState.js";
  2. import { MenuState } from "./states/MenuState.js";
  3. import { FiniteStateMachine } from "../libraries/FiniteStateMachine.js";
  4. import { AsyncDataReader } from "../libraries/AsyncDataReader.js";
  5. import { LevelSelectState } from "./states/LevelSelectState.js";
  6. export class Game {
  7. constructor() {
  8. this.stateMachine = new FiniteStateMachine();
  9. this.stateMachine.registerState("game", new GameState(this.stateMachine))
  10. this.stateMachine.registerState("menu", new MenuState(this.stateMachine))
  11. this.stateMachine.registerState("levelselect", new LevelSelectState(this.stateMachine))
  12. }
  13. async init() {
  14. await this.loadLevelData();
  15. await this.loadPlayerData();
  16. this.stateMachine.setCurrentState("menu");
  17. this.stateMachine.getCurrentState().init();
  18. }
  19. async loadLevelData() {
  20. let levelData = await new AsyncDataReader().readJson("./js/game/leveldata/levels.json");
  21. this.stateMachine.getState("game").setLevelData(levelData);
  22. this.stateMachine.getState("levelselect").setLevelData(levelData);
  23. return levelData;
  24. }
  25. async loadPlayerData() {
  26. let playerData = localStorage.getItem("ballsort-playerdata");
  27. if(!playerData) {
  28. playerData = {level: 1};
  29. localStorage.setItem('ballsort-playerdata', JSON.stringify(playerData));
  30. } else {
  31. playerData = JSON.parse(playerData);
  32. }
  33. this.stateMachine.getState("game").setPlayerData(playerData);
  34. this.stateMachine.getState("levelselect").setPlayerData(playerData);
  35. return playerData;
  36. }
  37. draw(ctx, scaledCanvas) {
  38. this.stateMachine.getCurrentState().draw(ctx, scaledCanvas);
  39. }
  40. update(delta) {
  41. this.stateMachine.getCurrentState().update(delta);
  42. }
  43. }