LaunchStateMachine.ts 1.5 KB

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