-
Notifications
You must be signed in to change notification settings - Fork 0
/
passcode.tsx
78 lines (64 loc) · 2.23 KB
/
passcode.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
70
71
72
73
74
75
76
77
78
import React, { useRef, useState } from "react";
import ReactDOM from "react-dom";
import { createNanoEvents, createUseEvent, createUseEventRpc, rpcEmit, Response } from "react-simple-events";
import { PromiseCompletionSource } from "promise-completion-source";
interface GameEvents {
start(): void;
message(message: string): void;
passcode(resp: Response<Promise<string>>): void;
correct(): void;
incorrect(): void;
}
const gameEmitter = createNanoEvents<GameEvents>();
const useGameEvent = createUseEvent(gameEmitter);
const useGameEventRpc = createUseEventRpc(gameEmitter);
function App() {
const [display, setDisplay] = useState(<span>Nothing has happened yet...</span>);
useGameEvent("message", (message) => setDisplay(<h1>{message}</h1>));
useGameEvent("correct", () => setDisplay(<h1 style={{ color: "lime" }}>Correct!</h1>));
useGameEvent("incorrect", () => setDisplay(<h1 style={{ color: "red" }}>Incorrect!</h1>));
return (
<>
<button onClick={gameThread}>Start</button>
<div>
<AskInput />
{display}
</div>
</>
);
}
function AskInput() {
const [askHandle, setAskHandle] = useState<null | PromiseCompletionSource<string>>(null);
const inputBox = useRef<HTMLInputElement>(null);
useGameEventRpc("passcode", () => {
const source = new PromiseCompletionSource<string>();
setAskHandle(source);
return source.promise;
}, [setAskHandle]
);
if (askHandle == null) return null;
const submit = () => askHandle.resolve(inputBox.current.value);
return (
<>
<button type="button" onClick={submit}>Submit the passcode</button>
<input ref={inputBox} type="text" />
</>
);
}
const sleep = (seconds: number) => new Promise((resolve) => setTimeout(() => resolve(undefined), seconds * 1000));
async function gameThread() {
for (let i = 3; i >= 1; i--) {
gameEmitter.emit("message", `${i}...`);
await sleep(1);
}
gameEmitter.emit("message", "Enter the passcode...");
const passcode = await rpcEmit(gameEmitter, "passcode");
if (passcode === "hunter1") {
gameEmitter.emit("correct");
} else {
gameEmitter.emit("incorrect");
await sleep(2);
await gameThread();
}
}
ReactDOM.render(<App />, document.getElementById("root"));