forked from tom-james-watson/wikitrivia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathitems.ts
61 lines (53 loc) · 1.64 KB
/
items.ts
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
import { Item, PlayedItem } from "../types/item";
import { createWikimediaImage } from "./image";
export function getRandomItem(deck: Item[], played: Item[]): Item {
const periods: [number, number][] = [
[-100000, 1000],
[1000, 1800],
[1800, 2020],
];
const [fromYear, toYear] =
periods[Math.floor(Math.random() * periods.length)];
const avoidPeople = Math.random() > 0.5;
const candidates = deck.filter((candidate) => {
if (avoidPeople && candidate.instance_of.includes("human")) {
return false;
}
if (candidate.year < fromYear || candidate.year > toYear) {
return false;
}
if (tooClose(candidate, played)) {
return false;
}
return true;
});
if (candidates.length > 0) {
return candidates[Math.floor(Math.random() * candidates.length)];
}
return deck[Math.floor(Math.random() * deck.length)];
}
function tooClose(item: Item, played: Item[]) {
let distance = (played.length < 40) ? 5 : 1;
if (played.length < 11)
distance = 110 - 10 * played.length;
return played.some((p) => Math.abs(item.year - p.year) < distance);
}
export function checkCorrect(
played: PlayedItem[],
item: Item,
index: number
): { correct: boolean; delta: number } {
const sorted = [...played, item].sort((a, b) => a.year - b.year);
const correctIndex = sorted.findIndex((i) => {
return i.id === item.id;
});
if (index !== correctIndex) {
return { correct: false, delta: correctIndex - index };
}
return { correct: true, delta: 0 };
}
export function preloadImage(url: string): HTMLImageElement {
const img = new Image();
img.src = createWikimediaImage(url);
return img;
}