LaunchStateMachine.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { AppKernel } from '../../app/AppKernel';
  2. import { AsyncStateMachine } from '../../framework/state/AsyncStateMachine';
  3. import { CheckVersionState } from './states/CheckVersionState';
  4. import { CompleteState } from './states/CompleteState';
  5. import { EnterLobbyState } from './states/EnterLobbyState';
  6. import { FailedState } from './states/FailedState';
  7. import { HotUpdateState } from './states/HotUpdateState';
  8. import {
  9. LaunchContext,
  10. LaunchProgress,
  11. LaunchState,
  12. LaunchStateId,
  13. } from './states/LaunchState';
  14. import { PreloadLobbyState } from './states/PreloadLobbyState';
  15. export type { LaunchProgress } from './states/LaunchState';
  16. export type LaunchProgressHandler = (value: LaunchProgress) => void;
  17. /**
  18. * 启动业务状态机。
  19. *
  20. * 负责版本检测、热更新、资源预加载、场景切换和统一失败处理,
  21. */
  22. export class LaunchStateMachine {
  23. private readonly machine = new AsyncStateMachine<LaunchStateId>();
  24. constructor(private readonly context: LaunchContext) {
  25. this.registerStates();
  26. }
  27. get current(): LaunchStateId | null {
  28. return this.machine.current;
  29. }
  30. async run(): Promise<void> {
  31. try {
  32. await this.machine.start(LaunchStateId.CheckVersion);
  33. } catch (error) {
  34. this.context.error = error;
  35. await this.machine.transition(LaunchStateId.Failed);
  36. }
  37. }
  38. private registerStates(): void {
  39. const states: LaunchState[] = [
  40. new CheckVersionState(),
  41. new HotUpdateState(),
  42. new PreloadLobbyState(),
  43. new EnterLobbyState(),
  44. new CompleteState(),
  45. new FailedState(),
  46. ];
  47. for (const state of states) {
  48. this.machine.register(state.id, () => state.enter(this.context));
  49. }
  50. }
  51. }