-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathgame.tsx
83 lines (73 loc) · 2.3 KB
/
game.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
import React, { useState } from "react";
import axios from "axios";
import { GameState } from "../types/game";
import { Item } from "../types/item";
import createState from "../lib/create-state";
import Board from "./board";
import Loading from "./loading";
import Instructions from "./instructions";
import badCards from "../lib/bad-cards";
export default function Game() {
const [state, setState] = useState<GameState | null>(null);
const [loaded, setLoaded] = useState(false);
const [started, setStarted] = useState(false);
const [items, setItems] = useState<Item[] | null>(null);
React.useEffect(() => {
const fetchGameData = async () => {
const res = await axios.get<string>("/items.json");
const items: Item[] = res.data
.trim()
.split("\n")
.map((line) => {
return JSON.parse(line);
})
// Filter out questions which give away their answers
.filter((item) => !item.label.includes(String(item.year)))
.filter((item) => !item.description.includes(String(item.year)))
.filter((item) => !/(?:th|st|nd)[ -]century/i.test(item.description))
// Filter cards which have bad data as submitted in https://github.com/tom-james-watson/wikitrivia/discussions/2
.filter((item) => !(item.id in badCards));
setItems(items);
};
fetchGameData();
}, []);
React.useEffect(() => {
(async () => {
if (items !== null) {
setState(await createState(items));
setLoaded(true);
}
})();
}, [items]);
const resetGame = React.useCallback(() => {
(async () => {
if (items !== null) {
setState(await createState(items));
}
})();
}, [items]);
const [highscore, setHighscore] = React.useState<number>(
Number(localStorage.getItem("highscore") ?? "0")
);
const updateHighscore = React.useCallback((score: number) => {
localStorage.setItem("highscore", String(score));
setHighscore(score);
}, []);
if (!loaded || state === null) {
return <Loading />;
}
if (!started) {
return (
<Instructions highscore={highscore} start={() => setStarted(true)} />
);
}
return (
<Board
highscore={highscore}
state={state}
setState={setState}
resetGame={resetGame}
updateHighscore={updateHighscore}
/>
);
}