Skip to content

Commit 95e373c

Browse files
committed
fix: code improvements + reviews suggestions
1 parent bc17341 commit 95e373c

File tree

8 files changed

+104
-300
lines changed

8 files changed

+104
-300
lines changed

examples/vanilla/phaser/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
"devDependencies": {
1212
"typescript": "^5.5.4",
1313
"vite": "^5.3.5",
14+
"vite-plugin-top-level-await": "^1.4.2",
1415
"vite-plugin-wasm": "^3.3.0"
1516
},
1617
"dependencies": {

examples/vanilla/phaser/src/dojo/defineContractSystems.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ const handleError = (action: string, error: unknown) => {
1616

1717
export type IWorld = Awaited<ReturnType<typeof setupWorld>>;
1818

19-
export async function setupWorld(provider: DojoProvider, config: Config) {
19+
export async function setupWorld(provider: DojoProvider, _config: Config) {
2020
const actions = () => ({
2121
spawn: async ({ account }: { account: AccountInterface }) => {
2222
try {

examples/vanilla/phaser/src/dojo/setup.ts

Lines changed: 65 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -10,57 +10,90 @@ import { setupWorld } from "./defineContractSystems.ts";
1010

1111
import { DojoProvider } from "@dojoengine/core";
1212
import { BurnerManager } from "@dojoengine/create-burner";
13-
import { Account, RpcProvider, wallet } from "starknet";
14-
import { createClientComponents } from "./createClientComponent.ts";
13+
import { Account, RpcProvider } from "starknet";
14+
import {
15+
ClientComponents,
16+
createClientComponents,
17+
} from "./createClientComponent.ts";
1518

1619
export type SetupResult = Awaited<ReturnType<typeof setup>>;
1720
export type IDojo = Awaited<ReturnType<typeof setup>>;
1821

1922
export async function setup({ ...config }: Config) {
2023
// torii client
21-
const toriiClient = await torii.createClient({
22-
rpcUrl: config.rpcUrl,
23-
toriiUrl: config.toriiUrl,
24-
relayUrl: "",
25-
worldAddress: config.manifest.world.address || "",
26-
});
24+
let toriiClient = null;
25+
try {
26+
toriiClient = await torii.createClient({
27+
rpcUrl: config.rpcUrl,
28+
toriiUrl: config.toriiUrl,
29+
relayUrl: "",
30+
worldAddress: config.manifest.world.address || "",
31+
});
32+
} catch (e) {
33+
console.error("Failed to create torii client:", e);
34+
throw e;
35+
}
2736

2837
// create contract components
29-
const contractModels = createClientComponents({
30-
contractComponents: defineContractComponents(world),
31-
});
38+
let contractModels = null;
39+
try {
40+
contractModels = createClientComponents({
41+
contractComponents: defineContractComponents(world),
42+
});
43+
} catch (e) {
44+
console.error("Failed to create contract components:", e);
45+
throw e;
46+
}
3247

3348
// create client components
3449
const { models: clientModels } = models({ contractModels });
3550

3651
// fetch all existing entities from torii
37-
const sync = await getSyncEntities(
38-
toriiClient,
39-
contractModels as any,
40-
[],
41-
1000
42-
);
52+
let sync = null;
53+
try {
54+
sync = await getSyncEntities(
55+
toriiClient,
56+
contractModels as any,
57+
[],
58+
1000
59+
);
60+
} catch (e) {
61+
console.error("Failed to fetch sync:", e);
62+
throw e;
63+
}
4364

44-
const client = await setupWorld(
45-
new DojoProvider(config.manifest, config.rpcUrl),
46-
config
47-
);
65+
let client = null;
66+
try {
67+
client = await setupWorld(
68+
new DojoProvider(config.manifest, config.rpcUrl),
69+
config
70+
);
71+
} catch (e) {
72+
console.error("Failed to create client:", e);
73+
throw e;
74+
}
4875

4976
const rpcProvider = new RpcProvider({
5077
nodeUrl: config.rpcUrl,
5178
});
5279

53-
const burnerManager = new BurnerManager({
54-
masterAccount: new Account(
55-
rpcProvider,
56-
config.masterAddress,
57-
config.masterPrivateKey
58-
),
59-
feeTokenAddress: config.feeTokenAddress,
60-
accountClassHash: config.accountClassHash,
80+
let burnerManager = null;
81+
try {
82+
burnerManager = new BurnerManager({
83+
masterAccount: new Account(
84+
rpcProvider,
85+
config.masterAddress,
86+
config.masterPrivateKey
87+
),
88+
feeTokenAddress: config.feeTokenAddress,
89+
accountClassHash: config.accountClassHash,
6190

62-
rpcProvider,
63-
});
91+
rpcProvider,
92+
});
93+
} catch (e) {
94+
console.log("Failed to create burner manager:", e);
95+
throw e;
96+
}
6497

6598
try {
6699
await burnerManager.init();
@@ -72,7 +105,7 @@ export async function setup({ ...config }: Config) {
72105
}
73106
const actions = systems({
74107
client,
75-
clientModels,
108+
clientModels: clientModels as ClientComponents,
76109
contractComponents: contractModels,
77110
});
78111
const account = burnerManager.getActiveAccount();

examples/vanilla/phaser/src/dojo/systems.ts

Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -45,22 +45,19 @@ export function systems({
4545
});
4646

4747
try {
48-
const { transaction_hash } = await client.actions.spawn({
48+
const { transaction_hash } = (await client.actions.spawn({
4949
account,
50-
});
51-
// setComponentsFromEvents(
52-
// contractComponents,
53-
// getEvents(
54-
// await account.waitForTransaction(transaction_hash, {
55-
// retryInterval: 100,
56-
// })
57-
// )
58-
// );
50+
})) as { transaction_hash: string };
51+
setComponentsFromEvents(
52+
contractComponents,
53+
getEvents(
54+
await account.waitForTransaction(transaction_hash, {
55+
retryInterval: 100,
56+
})
57+
)
58+
);
5959
} catch (e) {
60-
console.log(e);
61-
Position.removeOverride(positionId);
62-
Moves.removeOverride(movesId);
63-
} finally {
60+
console.error(e);
6461
Position.removeOverride(positionId);
6562
Moves.removeOverride(movesId);
6663
}
@@ -74,7 +71,6 @@ export function systems({
7471
BigInt(account.address),
7572
]) as Entity;
7673

77-
console.log(direction, getComponentValue(Position, entityId));
7874
const positionId = uuid();
7975
Position.addOverride(positionId, {
8076
entity: entityId,
@@ -99,10 +95,10 @@ export function systems({
9995
});
10096

10197
try {
102-
const { transaction_hash } = await client.actions.move({
98+
const { transaction_hash } = (await client.actions.move({
10399
account,
104100
direction,
105-
});
101+
})) as { transaction_hash: string };
106102

107103
setComponentsFromEvents(
108104
contractComponents,
@@ -116,9 +112,6 @@ export function systems({
116112
console.error(e);
117113
Position.removeOverride(positionId);
118114
Moves.removeOverride(movesId);
119-
} finally {
120-
Position.removeOverride(positionId);
121-
Moves.removeOverride(movesId);
122115
}
123116
};
124117
return { spawn, move };

examples/vanilla/phaser/src/dojo/utils.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,6 @@ export function updatePositionWithDirection(
99
direction: Direction,
1010
value: { vec: { x: number; y: number } }
1111
) {
12-
console.log(value);
13-
debugger;
1412
switch (direction) {
1513
case Direction.Left:
1614
value.vec.x--;

examples/vanilla/phaser/src/scenes/scene-main.ts

Lines changed: 19 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ export default class SceneMain extends Scene {
88
tileSize: number;
99
cameraSpeed: number;
1010
followPoint?: Phaser.Math.Vector2;
11-
chunks: Chunk[];
11+
chunks: Map<String, Chunk>;
1212
keyW: Phaser.Input.Keyboard.Key | null;
1313
keyS: Phaser.Input.Keyboard.Key | null;
1414
keyA: Phaser.Input.Keyboard.Key | null;
@@ -21,11 +21,12 @@ export default class SceneMain extends Scene {
2121
this.chunkSize = 16;
2222
this.tileSize = 16;
2323
this.cameraSpeed = 2;
24-
this.chunks = [];
24+
this.chunks = new Map<string, Chunk>();
2525
this.keyW = null;
2626
this.keyS = null;
2727
this.keyA = null;
2828
this.keyD = null;
29+
this.followPoint = new Phaser.Math.Vector2(0, 0);
2930
}
3031
preload() {
3132
this.load.spritesheet("sprWater", "assets/sprWater.png", {
@@ -75,11 +76,9 @@ export default class SceneMain extends Scene {
7576
}
7677

7778
getChunk(x: number, y: number) {
78-
var chunk = null;
79-
for (var i = 0; i < this.chunks.length; i++) {
80-
if (this.chunks[i].x == x && this.chunks[i].y == y) {
81-
chunk = this.chunks[i];
82-
}
79+
let chunk = this.chunks.get(`${x},${y}`);
80+
if (chunk === undefined) {
81+
return null;
8382
}
8483
return chunk;
8584
}
@@ -88,10 +87,7 @@ export default class SceneMain extends Scene {
8887
if (this.followPoint === null || this.followPoint === undefined) {
8988
throw new Error("failed to initialize followPoint");
9089
}
91-
if (
92-
this.checkInputs([this.keyA, this.keyD, this.keyW, this.keyS]) ===
93-
false
94-
) {
90+
if (!this.checkInputs([this.keyA, this.keyD, this.keyW, this.keyS])) {
9591
throw new Error("failed to initialize inputs");
9692
}
9793
var snappedChunkX =
@@ -106,19 +102,19 @@ export default class SceneMain extends Scene {
106102
snappedChunkX = snappedChunkX / this.chunkSize / this.tileSize;
107103
snappedChunkY = snappedChunkY / this.chunkSize / this.tileSize;
108104

109-
for (var x = snappedChunkX - 2; x < snappedChunkX + 2; x++) {
110-
for (var y = snappedChunkY - 2; y < snappedChunkY + 2; y++) {
111-
var existingChunk = this.getChunk(x, y);
105+
for (let x = snappedChunkX - 2; x < snappedChunkX + 2; x++) {
106+
for (let y = snappedChunkY - 2; y < snappedChunkY + 2; y++) {
107+
const existingChunk = this.getChunk(x, y);
112108

113-
if (existingChunk == null) {
114-
var newChunk = new Chunk(this, x, y);
115-
this.chunks.push(newChunk);
109+
if (existingChunk !== null) {
110+
continue;
116111
}
112+
this.chunks.set(`${x},${y}`, new Chunk(this, x, y));
117113
}
118114
}
119115

120-
for (var i = 0; i < this.chunks.length; i++) {
121-
var chunk = this.chunks[i];
116+
for (const [_, chunk] of this.chunks) {
117+
if (chunk === null) continue;
122118

123119
if (
124120
Phaser.Math.Distance.Between(
@@ -128,14 +124,10 @@ export default class SceneMain extends Scene {
128124
chunk.y
129125
) < 3
130126
) {
131-
if (chunk !== null) {
132-
chunk.load();
133-
}
134-
} else {
135-
if (chunk !== null) {
136-
chunk.unload();
137-
}
127+
chunk.load();
128+
continue;
138129
}
130+
chunk.unload();
139131
}
140132

141133
if (null !== this.keyW && this.keyW.isDown) {
@@ -167,7 +159,7 @@ export default class SceneMain extends Scene {
167159
}
168160

169161
private checkInputs(inputs: (Phaser.Input.Keyboard.Key | null)[]): boolean {
170-
for (var i = 0; i < inputs.length; i++) {
162+
for (let i = 0; i < inputs.length; i++) {
171163
if (inputs[i] === null || inputs[i] === undefined) {
172164
return false;
173165
}

examples/vanilla/phaser/vite.config.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
import path from "path";
22
import { defineConfig } from "vite";
33
import wasm from "vite-plugin-wasm";
4+
import topLevelAwait from "vite-plugin-top-level-await";
45

56
// https://vitejs.dev/config/
67
export default defineConfig({
7-
plugins: [wasm()],
8+
plugins: [wasm(), topLevelAwait()],
89
resolve: {
910
alias: {
1011
"@": path.resolve(__dirname, "./src"),

0 commit comments

Comments
 (0)