-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
385 lines (339 loc) · 10.5 KB
/
main.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
"use strict";
const stimuliTypes = [
'position',
'audio',
'color',
'shape',
];
// Normalize/fix settings over app versions
const normalizeSettings = settings => {
settings.audio.set = settings.audio.set || 'fi_automatic';
settings.color.set = settings.color.set || 'high_contrast';
settings.buttonOrder = settings.buttonOrder || structuredClone(stimuliTypes);
return settings;
}
const patchHistorySettings = entry => {
// Patch for old settings where bias was not set, but we accidentally overwrote it to 0.1.
// endMoment was introduced in the same version, so it's missing iff actionBias should be missing
// To avoid permantly destroying data if this reasoning is wrong, we save it to backup__actionBias as well.
if (entry.endMoment === undefined) {
if (entry.settings.backup__actionBias === undefined) {
entry.settings.backup__actionBias = entry.settings.actionBias;
}
entry.settings.actionBias = 0.0;
} else if (entry.settings.actionBias === undefined) {
entry.settings.actionBias = 0.1;
}
return entry;
};
const defaultSettings = normalizeSettings({
n: 2,
secondsPerTrial: 3,
runLength: 100,
actionBias: 0.1,
position: {
enabled: true,
key: 'a',
},
audio: {
enabled: true,
key: 'l',
set: 'fi_automatic'
},
color: {
enabled: false,
key: 'k',
set: 'high_contrast',
},
shape: {
enabled: false,
key: 's',
},
});
const audios = [
'fi_automatic',
'fi_dento_numerot',
'en_automatic',
];
const colors = {
"high_contrast": [
"red",
"green",
"blue",
"yellow",
"#a61",
"indigo",
"fuchsia",
"black",
"white"
],
"colorblind": [
"#332288",
"#117733",
"#44AA99",
"#88CCEE",
"#DDCC77",
"#CC6677",
"#AA4499",
"#882255",
"#ffffff",
],
"confusing": [
"red",
"pink",
"orange",
"salmon",
"green",
"lime",
"olive",
"limegreen",
"lawngreen",
]
};
const readSettings = () => {
const settingsStr = localStorage.getItem('settings');
if (settingsStr === null) {
writeSettings(defaultSettings);
return defaultSettings;
}
try {
return normalizeSettings(JSON.parse(settingsStr));
} catch {
writeSettings(defaultSettings);
return defaultSettings;
}
};
const writeSettings = settings => {
localStorage.setItem('settings', JSON.stringify(settings));
};
const updateSettings = () => {
let ok = document.getElementById('settings').checkValidity();
if (ok) {
let settings = Alpine.store('settings');
writeSettings(settings);
}
let state = Alpine.store('state');
state.hasValidSettings = ok;
};
let audioCtx = new Audio();
const startGame = () => {
document.getElementById('menu').close();
let state = Alpine.store('state');
state.currentRun = [];
state.selectedRun = readRunHistory().length; // For stat display and checking for ongoing game
setTimeout(stepGame, 1000);
};
const stepGame = () => {
let settings = Alpine.store('settings');
let perTrial = Number.parseFloat(settings.secondsPerTrial);
let state = Alpine.store('state');
stepCheckPrev(state);
if (state.currentRun.length >= settings.runLength) {
setTimeout(endGame, perTrial * 1000);
return;
}
// Run the current trial
let timeDelay = 0.1;
let timePrimary = 0.4;
let timePost = perTrial - timeDelay - timePrimary;
setTimeout(stepPrimary, timeDelay * 1000);
if (timePost > 0) {
setTimeout(stepPost, timePost * 1000);
}
setTimeout(stepGame, perTrial * 1000);
}
const stepCheckPrev = state => {
// Check previous trial, if any, and flash error responses
if (state.currentRun.length !== 0) {
let correct = checkCorrect();
state.currentRun.at(-1).correct = correct;
for (let k of Object.keys(correct)) {
document.querySelector("#responses ." + k).setAttribute('data-correct', correct[k]);
}
}
setTimeout(() => {
for (let r of document.querySelectorAll("#responses *[data-correct]")) {
r.removeAttribute('data-correct');
}
}, 400);
}
let stimuliStartedAt = null;
const stepPrimary = () => {
let settings = Alpine.store('settings');
let state = Alpine.store('state');
let nback = state.currentRun.at(-settings.n);
// Create entry and append to current run
let entry = {
response: {},
latency: {},
};
if (settings.position.enabled) {
if (nback !== undefined && Math.random() < settings.actionBias) {
entry.position = nback.position;
} else {
entry.position = Math.floor(Math.random() * 9);
}
}
if (settings.audio.enabled) {
if (nback !== undefined && Math.random() < settings.actionBias) {
entry.audio = nback.audio;
} else {
entry.audio = Math.floor(Math.random() * 9);
}
}
if (settings.color.enabled) {
if (nback !== undefined && Math.random() < settings.actionBias) {
entry.color = nback.color;
} else {
entry.color = Math.floor(Math.random() * 9);
}
}
if (settings.shape.enabled) {
if (nback !== undefined && Math.random() < settings.actionBias) {
entry.shape = nback.shape;
} else {
entry.shape = Math.floor(Math.random() * 9);
}
}
state.currentRun.push(entry);
// Activate relevant stimuli
for (let cell of document.querySelectorAll('#gamegrid>div')) {
cell.classList.remove('active');
}
let active = settings.position.enabled ? entry.position + 1 : 5;
let ac = document.querySelector('#gamegrid>div:nth-child(' + active + ')');
ac.classList.add('active');
ac.style.setProperty('--color', settings.color.enabled ? colors[settings.color.set][entry.color] : "#00f");
if (settings.audio.enabled) {
audioCtx.src = 'audio/' + settings.audio.set + '/' + (entry.audio + 1) + '.mp3';
audioCtx.play();
}
stimuliStartedAt = performance.now();
};
const stepPost = () => {
for (let cell of document.querySelectorAll('#gamegrid>div')) {
cell.classList.remove('active');
}
};
const checkCorrect = () => {
let settings = Alpine.store('settings');
let state = Alpine.store('state');
let correct = {};
if (settings.position.enabled) {
correct.position = false;
}
if (settings.audio.enabled) {
correct.audio = false;
}
if (settings.color.enabled) {
correct.color = false;
}
if (settings.shape.enabled) {
correct.shape = false;
}
if (state.currentRun.length <= settings.n) {
for (let k of Object.keys(correct)) {
correct[k] = !(k in state.currentRun.at(-1).response);
}
} else {
let lookback = state.currentRun.at(-(settings.n + 1));
let current = state.currentRun.at(-1);
for (let k of Object.keys(correct)) {
let resp = k in current.response;
let actual = lookback[k] == current[k];
correct[k] = resp === actual;
}
}
return correct;
};
const endGame = () => {
updateRunHistory();
setTimeout(() => {
document.getElementById('runstats').showModal();
}, 0); // Allow the browser to update the DOM before
}
const readRunHistory = () => {
return JSON.parse(localStorage.getItem('history') || '[]').map(patchHistorySettings).map(run => {
run.settings = normalizeSettings(run.settings);
return run;
});
};
const updateRunHistory = () => {
let state = Alpine.store('state');
let settings = Alpine.store('settings');
localStorage.getItem('history');
let history = readRunHistory();
let newHistory = history.concat([{
endMoment: (new Date()).toISOString(),
settings,
run: state.currentRun,
}]);
localStorage.setItem('history', JSON.stringify(newHistory));
Alpine.store('runHistory', newHistory);
};
const downloadRunHistory = () => {
let runHistory = Alpine.store('runHistory');
let fDate = getLocalNowISO().replace(/[:]/g, '').replace(' ', '-');
downloadTextFile("history-" + fDate + ".json", JSON.stringify(runHistory), "application/json");
};
const closeThisModal = event => {
let t = event.target;
while (t.tagName !== 'DIALOG') {
t = t.parentElement;
}
t.close();
};
const backToMenu = event => {
closeThisModal(event);
document.getElementById('menu').showModal();
checkForUpdates();
}
const sendResponse = category => {
let state = Alpine.store('state');
let latency = performance.now() - stimuliStartedAt; // ms
if (state.currentRun.length !== 0) {
let entry = state.currentRun.at(-1);
if (category === 'position') {
entry.response.position = true;
entry.latency.position = entry.latency.position || latency;
} else if (category === 'audio') {
entry.response.audio = true;
entry.latency.audio = entry.latency.audio || latency;
} else if (category === 'color') {
entry.response.color = true;
entry.latency.color = entry.latency.color || latency;
} else if (category === 'shape') {
entry.response.shape = true;
entry.latency.shape = entry.latency.shape || latency;
} else {
console.error("Unknown category", category);
}
}
};
document.addEventListener('alpine:init', () => {
Alpine.store('settings', readSettings());
Alpine.store('runHistory', readRunHistory());
Alpine.store('state', {
hasValidSettings: false,
currentRun: [],
selectedRun: null,
lang: 'fi',
});
setTimeout(updateSettings, 0);
document.getElementById('menu').showModal();
window.onkeydown = event => {
let settings = Alpine.store('settings');
let state = Alpine.store('state');
if (state.currentRun.length !== 0) {
if (event.key === settings.position.key) {
sendResponse('position');
} else if (event.key === settings.audio.key) {
sendResponse('audio');
} else if (event.key === settings.color.key) {
sendResponse('color');
} else if (event.key === settings.shape.key) {
sendResponse('shape');
}
}
};
})