-
Notifications
You must be signed in to change notification settings - Fork 0
/
TicTacToe.tsx
184 lines (168 loc) · 4.91 KB
/
TicTacToe.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
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
import { Actor, ActorState, StateBackedClient } from "@statebacked/client";
import { useStateBackedMachine } from "@statebacked/react";
import { useActor } from "@xstate/react";
import { ContextFrom, StateValueFrom } from "xstate";
import { ticTacToeMachine } from "../../statebacked/src/tic-tac-toe-machine";
import { getUserId } from "./auth";
import { useParams } from "react-router-dom";
import { useEffect, useState } from "react";
import styles from "./TicTacToe.module.css";
// we use anonymous sessions for our simple game.
// 0 setup required. all organizations enable anonymous access by default.
const client = new StateBackedClient({
anonymous: {
orgId: "org_uHvZHpF4STWvMg8BKVCUTg",
getSessionId() {
return getUserId();
},
},
});
type Event = Exclude<
Parameters<(typeof ticTacToeMachine)["transition"]>[1],
string
> & { [key: string]: unknown };
type State = StateValueFrom<typeof ticTacToeMachine>;
type Context = ContextFrom<typeof ticTacToeMachine>;
type OnlyPublicContext = Context["public"];
export default function TicTacToe() {
const { gameId } = useParams();
const { actor, error } = useStateBackedMachine<Event, State, Context>(
client,
{
machineName: "tic-tac-toe-example",
instanceName: gameId!,
getInitialContext() {
return { player1Id: getUserId() };
},
},
);
const [hashedUserId, setHashedUserId] = useState("");
useEffect(() => {
crypto.subtle
.digest("SHA-256", new TextEncoder().encode(getUserId()))
.then((hash) => {
setHashedUserId(btoa(String.fromCharCode(...new Uint8Array(hash))));
});
if (!actor) {
return;
}
actor.send({ type: "join", playerId: getUserId() });
}, [actor]);
if (error && !actor) {
return <div>Error: {error.message}</div>;
}
if (!actor) {
return <div>Loading...</div>;
}
return <Game actor={actor} hashedUserId={hashedUserId} />;
}
function Game({
actor,
hashedUserId,
}: {
actor: Actor<Event, State, OnlyPublicContext>;
hashedUserId: string;
}) {
const [state, send] = useActor(actor);
const arePlaying = state.matches("Playing");
const isGameOver = state.matches("Game over");
const waitingForPlayer2 = state.matches("Awaiting player 2");
const player =
hashedUserId === state.context.public.hashedPlayer1Id
? "player1"
: "player2";
const mark =
player === "player1"
? state.context.public.player1Mark
: state.context.public.player2Mark;
const ownWins = state.context.public.winners.filter(
(winner) => winner === player,
).length;
const opponentWins = state.context.public.winners.filter(
(winner) => winner !== player && winner !== "draw",
).length;
const draws = state.context.public.winners.length - ownWins - opponentWins;
const getWinner = (winner: "player1" | "player2" | "draw") => {
if (winner === "draw") {
return "Draw";
}
return winner === player ? "You won" : "You lost";
};
if (waitingForPlayer2) {
return (
<div>
<h2>Waiting for player 2</h2>
<p>
Send a friend this link or open a new browser tab to play yourself:{" "}
{window.location.href}
</p>
</div>
);
}
return (
<div>
<div>
<p>
Wins: {ownWins} Draws: {draws} Losses: {opponentWins}
</p>
<p>
You are playing as: <strong>{mark}</strong>
</p>
{arePlaying ? (
<>
{(state.matches("Playing.Awaiting x move") && mark === "x") ||
(state.matches("Playing.Awaiting o move") && mark === "o") ? (
<h2>Your move</h2>
) : (
<h2>Waiting for your opponent's move...</h2>
)}
<GameBoard state={state} send={send} />
</>
) : isGameOver ? (
<div>
<h3>{getWinner(state.context.public.winners.slice(-1)[0])}!</h3>
<button onClick={() => send({ type: "Play again" })}>
Play again
</button>
<GameBoard readonly state={state} send={send} />
</div>
) : null}
</div>
</div>
);
}
function GameBoard({
state,
send,
readonly,
}: {
state: ActorState<State, OnlyPublicContext>;
send: (event: Event) => void;
readonly?: boolean;
}) {
return (
<table className={styles.gameBoard}>
<tbody>
{state.context.public.board.map((row, rowIdx) => (
<tr key={rowIdx}>
{row.map((cell, cellIdx) => (
<td key={cellIdx}>
{cell || readonly ? (
<div>{cell}</div>
) : (
<button
onClick={() =>
send({ type: "move", row: rowIdx, column: cellIdx })
}
>
{cell}
</button>
)}
</td>
))}
</tr>
))}
</tbody>
</table>
);
}