-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathSimulation.tsx
69 lines (64 loc) · 1.64 KB
/
Simulation.tsx
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
import { useEffect, useRef, useState } from "react";
import { BallManager } from "../game/classes/BallManager";
import { WIDTH } from "../game/constants";
import { pad } from "../game/padding";
export function Simulation() {
const canvasRef = useRef<any>();
let [outputs, setOutputs] = useState<{ [key: number]: number[] }>({
0: [],
1: [],
2: [],
3: [],
4: [],
5: [],
6: [],
7: [],
8: [],
9: [],
10: [],
11: [],
12: [],
13: [],
14: [],
15: [],
16: [],
17: [],
});
async function simulate(ballManager: BallManager) {
let i = 0;
while (1) {
i++;
ballManager.addBall(pad(WIDTH / 2 + 20 * (Math.random() - 0.5)));
await new Promise((resolve) => setTimeout(resolve, 1000));
}
}
useEffect(() => {
if (canvasRef.current) {
const ballManager = new BallManager(
canvasRef.current as unknown as HTMLCanvasElement,
(index: number, startX?: number) => {
setOutputs((outputs: any) => {
return {
...outputs,
[index]: [...(outputs[index] as number[]), startX],
};
});
}
);
simulate(ballManager);
return () => {
ballManager.stop();
};
}
}, [canvasRef]);
return (
<div className="flex flex-col lg:flex-row items-center justify-between h-screen">
<div className="flex mx-16 flex-col justify-center pt-10">
{JSON.stringify(outputs, null, 2)}
</div>
<div className="flex flex-col items-center justify-center">
<canvas ref={canvasRef} width="800" height="800"></canvas>
</div>
</div>
);
}