File size: 5,756 Bytes
794cf6c
dd99b77
794cf6c
 
db9635c
bc7e9cd
 
 
 
794cf6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc7e9cd
dd99b77
db9635c
dd99b77
 
 
 
794cf6c
bc7e9cd
794cf6c
 
 
bc7e9cd
 
 
 
db9635c
bc7e9cd
 
 
 
 
 
 
 
 
 
794cf6c
bc7e9cd
 
 
 
 
dd99b77
bc7e9cd
 
dd99b77
bc7e9cd
 
db9635c
bc7e9cd
 
 
dd99b77
bc7e9cd
 
 
 
 
 
 
 
db9635c
794cf6c
 
 
bc7e9cd
794cf6c
dd99b77
794cf6c
 
 
 
 
bc7e9cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
794cf6c
 
 
dd99b77
bc7e9cd
794cf6c
dd99b77
794cf6c
 
 
 
 
 
 
bc7e9cd
794cf6c
dd99b77
 
794cf6c
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import * as GAME from "vibegame";
import type { System, Plugin, Component, BuilderOptions } from "vibegame";
import { gameStore } from "../stores/game";
import { uiStore } from "../stores/ui";
import { consoleBuffer } from "../server/console-buffer";
import {
  HTMLDocumentParser,
  type ParsedDocument,
} from "./html-document-parser";

type GameInstance = Awaited<ReturnType<typeof GAME.run>>;

export class GameEngine {
  private static instance: GameEngine | null = null;
  private gameInstance: GameInstance | null = null;

  private constructor() {}

  static getInstance(): GameEngine {
    if (!GameEngine.instance) {
      GameEngine.instance = new GameEngine();
    }
    return GameEngine.instance;
  }

  async startFromDocument(htmlContent: string): Promise<void> {
    if (this.gameInstance) {
      consoleBuffer.onGameReloadStart();
      this.stop();
      await new Promise((resolve) => setTimeout(resolve, 100));
    }

    gameStore.setStarting(true);
    console.info("๐ŸŽฎ Starting game...");
    uiStore.setError(null);

    try {
      const parsed = HTMLDocumentParser.parseDocument(htmlContent);
      this.renderDocument(parsed);
      await this.initializeGame(parsed.scripts);
      console.info("โœ… Game started!");
      consoleBuffer.onGameReloadComplete();
    } catch (error: unknown) {
      const errorMsg = error instanceof Error ? error.message : String(error);
      uiStore.setError(errorMsg);
      console.error(`โŒ Error: ${errorMsg}`);
      gameStore.setInstance(null);
      this.gameInstance = null;
    } finally {
      gameStore.setStarting(false);
    }
  }

  async start(worldContent: string, scripts: string[] = []): Promise<void> {
    const parsed: ParsedDocument = {
      world: worldContent,
      scripts,
    };

    await this.startFromParsed(parsed);
  }

  private async startFromParsed(parsed: ParsedDocument): Promise<void> {
    if (this.gameInstance) {
      consoleBuffer.onGameReloadStart();
      this.stop();
      await new Promise((resolve) => setTimeout(resolve, 100));
    }

    gameStore.setStarting(true);
    console.info("๐ŸŽฎ Starting game...");
    uiStore.setError(null);

    try {
      this.renderDocument(parsed);
      await this.initializeGame(parsed.scripts);
      console.info("โœ… Game started!");
      consoleBuffer.onGameReloadComplete();
    } catch (error: unknown) {
      const errorMsg = error instanceof Error ? error.message : String(error);
      uiStore.setError(errorMsg);
      console.error(`โŒ Error: ${errorMsg}`);
      gameStore.setInstance(null);
      this.gameInstance = null;
    } finally {
      gameStore.setStarting(false);
    }
  }

  private renderDocument(parsed: ParsedDocument): void {
    const container = document.getElementById("world-container");
    if (!container) {
      throw new Error("World container not found");
    }

    this.clearContainer(container);
    container.innerHTML = parsed.world;
  }

  private clearContainer(container: HTMLElement): void {
    while (container.firstChild) {
      container.removeChild(container.firstChild);
    }
  }

  private async initializeGame(scripts: string[]): Promise<void> {
    GAME.resetBuilder();

    const gameProxy = this.createGameProxy();
    (window as unknown as { GAME: typeof gameProxy }).GAME = gameProxy;

    let scriptExecutionFailed = false;
    for (const script of scripts) {
      try {
        const cleanedScript = script.replace(/GAME\.run\(\)/g, "");
        eval(cleanedScript);
      } catch (scriptError) {
        scriptExecutionFailed = true;
        const errorMsg =
          scriptError instanceof Error
            ? scriptError.message
            : String(scriptError);
        console.error("Script error:", errorMsg);
      }
    }

    (window as unknown as { GAME: typeof gameProxy | null }).GAME = null;

    if (scriptExecutionFailed) {
      throw new Error("Script execution failed - game not started");
    }

    this.gameInstance = await GAME.run();
    gameStore.setInstance(this.gameInstance);
  }

  private createGameProxy() {
    return {
      withSystem: (system: System) => {
        GAME.withSystem(system);
        return this.createGameProxy();
      },
      withPlugin: (plugin: Plugin) => {
        GAME.withPlugin(plugin);
        return this.createGameProxy();
      },
      withComponent: (name: string, component: Component) => {
        GAME.withComponent(name, component);
        return this.createGameProxy();
      },
      configure: (options: BuilderOptions) => {
        GAME.configure(options);
        return this.createGameProxy();
      },
      withoutDefaultPlugins: () => {
        GAME.withoutDefaultPlugins();
        return this.createGameProxy();
      },
      run: () => {
        console.warn(
          "GAME.run() is not available in user scripts - the framework handles game lifecycle",
        );
        return Promise.resolve({
          stop: () => {},
          destroy: () => {},
          step: () => {},
          getState: () => null,
        });
      },
      defineComponent: GAME.defineComponent,
      defineQuery: GAME.defineQuery,
      Types: GAME.Types,
    };
  }

  stop(): void {
    if (this.gameInstance) {
      try {
        this.gameInstance.destroy();
        console.info("Game instance destroyed");
      } catch (error) {
        console.error("Error destroying game:", error);
      }
      this.gameInstance = null;
      gameStore.setInstance(null);
    }

    const container = document.getElementById("world-container");
    if (container) {
      this.clearContainer(container);
    }

    GAME.resetBuilder();
  }

  isRunning(): boolean {
    return this.gameInstance !== null;
  }
}

export const gameEngine = GameEngine.getInstance();