| 5 | |
| 6 | |
| 7 | export function Simulation() { |
| 8 | const canvasRef = useRef<any>(); |
| 9 | let [outputs, setOutputs] = useState<{[key: number]: number[]}>({ |
| 10 | 0: [], |
| 11 | 1: [], |
| 12 | 2: [], |
| 13 | 3: [], |
| 14 | 4: [], |
| 15 | 5: [], |
| 16 | 6: [], |
| 17 | 7: [], |
| 18 | 8: [], |
| 19 | 9: [], |
| 20 | 10: [], |
| 21 | 11: [], |
| 22 | 12: [], |
| 23 | 13: [], |
| 24 | 14: [], |
| 25 | 15: [], |
| 26 | 16: [], |
| 27 | 17: [] |
| 28 | }); |
| 29 | |
| 30 | async function simulate(ballManager: BallManager) { |
| 31 | let i = 0; |
| 32 | while (1) { |
| 33 | i++ |
| 34 | ballManager.addBall(pad(WIDTH / 2 + 20 * (Math.random() - 0.5))) |
| 35 | await new Promise(resolve => setTimeout(resolve, 1000)); |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | useEffect(() => { |
| 40 | if (canvasRef.current) { |
| 41 | const ballManager = new BallManager(canvasRef.current as unknown as HTMLCanvasElement, (index: number, startX?: number) => { |
| 42 | setOutputs((outputs: any) => { |
| 43 | return { |
| 44 | ...outputs, |
| 45 | [index]: [...outputs[index] as number[], startX] |
| 46 | } |
| 47 | }) |
| 48 | }) |
| 49 | simulate(ballManager); |
| 50 | |
| 51 | return () => { |
| 52 | ballManager.stop(); |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | }, [canvasRef]) |
| 57 | |
| 58 | return ( |
| 59 | <div style={{display: "flex"}}> |
| 60 | <div style={{display: "flex", justifyContent: "center", alignItems: "center", flexDirection: "column", minHeight: "100vh"}}> |
| 61 | {JSON.stringify(outputs, null, 2)} |
| 62 | </div> |
| 63 | <div style={{display: "flex", justifyContent: "center", alignItems: "center", flexDirection: "column", minHeight: "100vh"}}> |
| 64 | <canvas ref={canvasRef} width="800" height="800"></canvas> |