-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathapp.js
171 lines (154 loc) · 5.66 KB
/
app.js
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
const buttonsElement = document.querySelector('#buttons');
const imageElement = document.querySelector('#image');
const correctScoreElement = document.querySelector('#correct-score');
const wrongScoreElement = document.querySelector('#wrong-score');
const approvedElement = document.querySelector('.approved');
const quakerOatsElement = document.querySelector('.oated');
const championsUrl = 'https://ddragon.leagueoflegends.com/cdn/9.3.1/data/en_US/champion.json';
const getChampionUrl = (champion) => `https://ddragon.leagueoflegends.com/cdn/11.7.1/data/en_US/champion/${champion}.json`;
const wrongSound = new Audio('/sounds/bad.mp3');
const correctSound = new Audio('/sounds/good.mp3');
const stampSound = new Audio('https://freesound.org/data/previews/362/362622_3165091-hq.mp3');
const gameState = {
classifier: null,
correctGuesses: 0,
wrongGuesses: 0,
};
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function getRandomIndex(array) {
return Math.floor(Math.random() * array.length);
}
function getRandomValue(array) {
const randomIndex = getRandomIndex(array);
return array[randomIndex];
}
async function getChampions() {
const response = await fetch(championsUrl);
const json = await response.json();
return Object.keys(json.data);
}
async function getChampionSkins(champion) {
const championUrl = getChampionUrl(champion);
const response = await fetch(championUrl);
const json = await response.json();
return {
champion,
skins: json.data[champion].skins,
};
}
function getRandomSkinUrl(info) {
const skin = getRandomValue(info.skins);
const skinUrl = `https://ddragon.leagueoflegends.com/cdn/img/champion/splash/${info.champion}_${skin.num}.jpg`;
return skinUrl;
}
// getChampions()
// .then(getRandomValue)
// .then(getChampionSkins)
// .then(displayChampionSkin)
// .catch(console.error);
function getRandomNumber() {
return Math.floor(Math.random() * 200);
}
async function getChampion() {
const champions = await getChampions();
const randomChampion = getRandomValue(champions);
const info = await getChampionSkins(randomChampion);
const skinUrl = getRandomSkinUrl(info);
imageElement.style.transform = `translateX(-${getRandomNumber()}%) translateY(-${getRandomNumber()}%) scale(3)`;
imageElement.src = skinUrl;
imageElement.setAttribute('crossOrigin', 'anonymous');
return new Promise((resolve) => {
const loaded = () => {
imageElement.removeEventListener('load', loaded);
resolve();
};
imageElement.addEventListener('load', loaded);
});
}
async function getSimilarWords(word) {
const response = await fetch(`https://api.datamuse.com/words?ml=${word}`);
const json = await response.json();
return json;
}
async function displayGuessButtons(randomLabel) {
const similarWords = await getSimilarWords(randomLabel);
const wordsToDisplay = similarWords.slice(0, 10).map((item) => item.word);
const randomIndex = getRandomIndex(wordsToDisplay);
wordsToDisplay.splice(randomIndex, 0, randomLabel);
wordsToDisplay.forEach((label) => {
const button = document.createElement('button');
button.textContent = label;
buttonsElement.appendChild(button);
button.addEventListener('click', () => userClickedGuess(randomLabel, label));
});
}
async function userClickedGuess(answer, guess) {
if (answer !== guess) {
wrongSound.currentTime = 0;
wrongSound.play();
await sleep(100);
const utterance = new SpeechSynthesisUtterance(`You are wrong! The answer was ${answer}`);
speechSynthesis.speak(utterance);
gameState.wrongGuesses += 1;
} else {
correctSound.currentTime = 0;
correctSound.play();
await sleep(100);
const utterance = new SpeechSynthesisUtterance('You are correct!');
speechSynthesis.speak(utterance);
gameState.correctGuesses += 1;
}
correctScoreElement.textContent = gameState.correctGuesses;
wrongScoreElement.textContent = gameState.wrongGuesses;
imageElement.style.transform = 'scale(1)';
buttonsElement.innerHTML = '';
if (gameState.correctGuesses >= 5 || gameState.wrongGuesses >= 5) {
if (gameState.correctGuesses >= 5) {
stampSound.currentTime = 0;
stampSound.play();
approvedElement.classList.remove('hidden');
const utterance = new SpeechSynthesisUtterance('Congratulations! You have been approved.');
speechSynthesis.speak(utterance);
} else {
stampSound.currentTime = 0;
stampSound.play();
quakerOatsElement.classList.remove('hidden');
const utterance = new SpeechSynthesisUtterance('You have failed. I am disappointed in you. Get oat.');
speechSynthesis.speak(utterance);
}
} else {
await sleep(3500);
await getChampion();
gameState.classifier.classify(document.querySelector('img'), (err, results) => {
if (results.length) {
const allLabels = results.reduce((labels, result) => labels.concat(result.label.split(', ')), []);
const randomLabel = getRandomValue(allLabels);
displayGuessButtons(randomLabel);
}
});
}
}
async function initialize() {
try {
const [classifier] = await Promise.all([
new Promise((resolve) => {
const cl = ml5.imageClassifier('MobileNet', () => resolve(cl));
}),
getChampion(),
]);
console.log('WE DID IT.');
gameState.classifier = classifier;
classifier.classify(document.querySelector('img'), (err, results) => {
if (results.length) {
const allLabels = results.reduce((labels, result) => labels.concat(result.label.split(', ')), []);
const randomLabel = getRandomValue(allLabels);
displayGuessButtons(randomLabel);
}
});
} catch (error) {
console.error(error);
}
}
initialize();