-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
563 lines (512 loc) · 19.6 KB
/
index.html
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-2E561F2422"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'G-2E561F2422');
</script>
<!--
************************************************
The script above is for google analytics.
You'll want to remove that if you use this page.
************************************************
-->
<title>Chroma - Daily Colour Game</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link type="text/css" rel="stylesheet" href="styles.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/seedrandom/3.0.5/seedrandom.min.js"></script>
<script src="colours.js"></script>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="icon" type="image/png" sizes="32x32" href="favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="favicon-16x16.png">
</head>
<body>
<div id="info">
<div id="set">
Today's Colours: <a id="colourSet"></a>
</div>
<div id="about">
<a href="https://github.com/Robson/Chroma">Code</a> by <a href="https://robson.plus">Robson</a>
</div>
</div>
<div id="progress">◇◇◇◇◇</div>
<div id="question"></div>
<div id="answers"></div>
<div id="result"><div id="extra"></div></div>
<div id="share">
<div id="copyResultsMobile" onclick="copyResultsAsText()">Copy Results</div>
<div id="copyResultsAsText" onclick="copyResultsAsText()">Copy Results as Text</div>
<br>
<div id="copyResultsAsImage" onclick="copyResultsAsImage()">Copy Results as Image</div>
</div>
<div id="save">
<div id="saveCookie" onclick="enableCookies()">Always Remember Results<br><span>🍪 this uses cookies 🍪</span></div>
</div>
<div id="next"><div id="nextLevel" onclick="showNewLevel()">Next Question</div></div>
<div id="finish"><div id="showResults" onclick="showResults()">Show Results</div></div>
<script>
function getCookie(name) {
const nameEQ = name + "=";
const cookiesArray = document.cookie.split(";");
for (let i = 0; i < cookiesArray.length; i++) {
let cookie = cookiesArray[i].trim();
if (cookie.indexOf(nameEQ) === 0) {
return decodeURIComponent(cookie.substring(nameEQ.length));
}
}
return null;
}
function setCookie(name, value, temporary) {
var expireDate = new Date();
if (temporary) {
expireDate.setTime((new Date()).getTime() + (7 * 24 * 60 * 60 * 1000));
} else {
expireDate.setTime((new Date()).getTime() + (365 * 24 * 60 * 60 * 1000));
}
let expires = "; expires=" + expireDate.toUTCString();
document.cookie = name + "=" + encodeURIComponent(value) + expires + "; path=/";
}
var isSavingResults = false;
if (getCookie('SaveResults') == '1') {
isSavingResults = true;
// resave for another year
setCookie('SaveResults', '1', temporary=false);
}
function saveResults() {
// remember that the user has chosen to accept cookies
setCookie('SaveResults', '1', temporary=false);
// save the result in case they come back later today
var answers = '';
for (var entry of tracker) {
answers += entry.clickedIndex;
}
setCookie('db' + daysBetween, answers, temporary=true);
}
function enableCookies() {
saveResults();
alert("Success! Your results will now be remember if you return later in the day.");
d3.select('#save').style('display', 'none');
}
var correctIndex;
var answers = [];
var tracker = [];
var fixedAnswers = null;
var hasPlayed = false;
const levels = 5;
var minimumDeltaDifference = 30;
function getDaysBetweenDates(startDate, endDate) {
const oneDay = 1000 * 60 * 60 * 24;
const start = Date.UTC(startDate.getFullYear(), startDate.getMonth(), startDate.getDate());
const end = Date.UTC(endDate.getFullYear(), endDate.getMonth(), endDate.getDate());
return Math.round((end - start) / oneDay);
}
const startDate = new Date(Date.UTC(2024, 9, 21));
const endDate = new Date();
var daysBetween = getDaysBetweenDates(startDate, endDate);
const now = new Date();
const month = now.getUTCMonth() + 1;
const date = now.getUTCDate();
var hash = date + '-' + month;
if (window.location.hash.substring(1) == 'random') {
daysBetween = Math.floor(Math.random() * 10000000);
}
if (window.location.hash.substring(1).length > 0) {
daysBetween = Math.floor(Math.random() * 10000000);
hash = window.location.hash.substring(1);
}
var rand = new Math.seedrandom('c' + daysBetween);
function weightedRandomChoice(items) {
const totalWeight = items.reduce((sum, item) => sum + item.weight, 0);
let randomWeight = rand() * totalWeight;
for (let item of items) {
randomWeight -= item.weight;
if (randomWeight <= 0) {
return item;
}
}
}
const schemes = [
{ weight: 45, arr: coloursPantoneFHI },
{ weight: 25, arr: coloursDuluxPopular },
{ weight: 10, arr: coloursDuluxHeritage },
{ weight: 10, arr: coloursFarrowBallSignature },
{ weight: 10, arr: coloursJapanTraditional }
];
var set = weightedRandomChoice(schemes).arr;
switch (hash) {
case '1-3': // saint david's day
set = coloursPantoneFHI;
fixedAnswers = [
'Leek Green',
'Mountain View',
'Daffodil',
'Dragon Fire',
'Lambs Wool',
];
shuffleArray(fixedAnswers);
break;
case '17-3': // saint patrick's day
set = coloursPantoneFHI;
fixedAnswers = [
'Irish Green',
'Shamrock',
'Blarney',
'Kelly Green',
'Irish Cream',
];
shuffleArray(fixedAnswers);
break;
case '23-4': // saint george's day
set = coloursPantoneFHI;
fixedAnswers = [
'English Rose',
'English Manor',
'English Ivy',
'English Lavendar',
'Royal Blue',
'London Fog',
'Dragon Fire',
];
shuffleArray(fixedAnswers);
break;
case '14-7': // bastille day
set = coloursPantoneFHI;
fixedAnswers = [
'Provence',
'Limoges',
'Bijou Blue',
'Parisian Blue',
'French Blue',
'Parisian Night',
'Eiffel Tower',
'French Roast',
'French Vanilla',
];
shuffleArray(fixedAnswers);
break;
case '31-10': // halloween
set = coloursPantoneFHI;
fixedAnswers = [
'Phantom',
'Pumpkin Spice',
'Midnight',
'Pumpkin',
'Purple Magic',
'Nightshadow Blue',
'Pureed Pumpkin',
'Harvest Pumpkin',
'Ghost Gray',
'Moonlight',
];
shuffleArray(fixedAnswers);
break;
case '5-11': // guy fawkes night
set = coloursPantoneFHI;
fixedAnswers = [
'Firecracker',
'Flame',
'Powder Blue',
'Powder Pink',
'Flame Scarlet',
];
shuffleArray(fixedAnswers);
break;
case '25-12': // christmas
set = coloursPantoneFHI;
fixedAnswers = [
'Winter White',
'Mistletoe',
'Holly Berry',
'Tinsel',
'Ribbon Red'
];
shuffleArray(fixedAnswers);
break;
}
var colours = set.items;
minimumDeltaDifference = set.deltaMinimum;
d3.select('#colourSet')
.attr('href', set.link)
.text(set.name);
// convert 0-255 rgb to hex rgb, if necessary
for (var a = 0; a < colours.length; a++) {
if (colours[a][1].includes(',')) {
colours[a][1] = colours[a][1].replace(/ /g, '');
var parts = colours[a][1].split(',');
colours[a][1] = parts.map(a => ('0' + (+a).toString(16)).slice(-2)).join('');
}
}
function ToTitleCase(str) {
return str.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(' ')
.split('(').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join('(');
}
for (var a = 0; a < colours.length; a++) {
colours[a][0] = ToTitleCase(colours[a][0]);
}
// convert names to Title Case, if necessary
if (colours[0][0] == colours[0][0].toLowerCase()) {
convertToTitleCase();
}
function shuffleArray(arr) {
for (let i = arr.length - 1; i >= 0; i--) {
const j = Math.floor(rand() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
function hexToRgb(hex) {
return {
r: parseInt(hex.slice(0, 2), 16),
g: parseInt(hex.slice(2, 4), 16),
b: parseInt(hex.slice(4, 6), 16)
};
}
function copyResultsAsText() {
var output = '#Chroma\r\n';
var d = new Date();
output += 'Challenge ' + (daysBetween + 1);
output += '\r\n';
for (var question of tracker) {
if (question.correct) {
output += '\r\n✅ '
} else {
output += '\r\n❌ '
}
output += question.items[question.correctIndex][0] + ' ';
}
navigator.clipboard.writeText(output);
alert("Result copied to the clipboard!");
}
function copyResultsAsImage() {
html2canvas(document.getElementById('result')).then(canvas => {
canvas.toBlob(function(blob) {
navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })])
.then(() => {
alert("Result copied to the clipboard!");
})
.catch(err => {
alert("Something went wrong whilst copying the image to the clipboard :(");
});
});
});
}
function showResults() {
if (!isSavingResults) {
d3.select('#save').style('display', 'block');
} else {
saveResults();
}
d3.select('#answers').style('display', 'none');
d3.select('#finish').style('display', 'none');
d3.select('#progress').style('display', 'none');
d3.select('#question').style('display', 'none');
d3.select('#share').style('display', 'block');
d3.select('#info #about').style('display', 'block');
d3.select('#result').style('display', 'inline-block');
var amountCorrect = tracker.filter(a => a.correct).length;
var exclamation = '';
if (amountCorrect == levels) {
exclamation = '. Perfect!';
} else if (amountCorrect == levels - 1) {
exclamation = '. Excellent!';
}
var resultBox = d3.select('#result');
var extraBox = d3.select('#extra');
extraBox.style('display', 'block');
var d = new Date();
var celebrateEmoji = ['🎈','🎆','✨','🎉','🎊','🎨','💎','🏅','🏆','🚀','🌈'];
celebrateEmoji = celebrateEmoji[~~(rand() * celebrateEmoji.length)];
extraBox
.append('div')
.html('Chroma<br/>' +
'Challenge ' + (daysBetween + 1) + '<br/>' +
(amountCorrect == levels ? '<span class="emoji">' + celebrateEmoji + '</span> Completely Correct! <span class="emoji">' + celebrateEmoji + '</span>': amountCorrect + ' correct out of ' + levels));
for (var question of tracker) {
var line = resultBox.append('div');
line.append('p').html(question.items[question.correctIndex][0]);
var miniAnswers = line.append('div');
miniAnswers.classed('answerMini');
for (var index in question.items) {
var circle = question.items[index];
var rgb = hexToRgb(circle[1]);
var hsp = Math.sqrt(
0.299 * (rgb.r * rgb.r) +
0.587 * (rgb.g * rgb.g) +
0.114 * (rgb.b * rgb.b)
);
var resultClass = '';
if (+index == +question.correctIndex) {
resultClass = ' yes_' + (hsp > 127.5 ? 'black' : 'white');
} else if (+index == +question.clickedIndex) {
resultClass = ' no_' + (hsp > 127.5 ? 'black' : 'white');
}
miniAnswers
.append('div')
.attr('class', 'answersMini' + resultClass)
.attr('title', circle[0])
.style('background-color', '#' + circle[1]);
}
}
d3.select('#share')
.append('p')
.html("Come back tomorrow for a new set of colours!");
}
function clickAnswer(index) {
var log = {
clickedIndex: index,
correctIndex: correctIndex,
correct: index == correctIndex,
items: answers.slice(0)
}
for (var a = 0; a < answers.length; a++) {
var rgb = hexToRgb(answers[a][1]);
var hsp = Math.sqrt(
0.299 * (rgb.r * rgb.r) +
0.587 * (rgb.g * rgb.g) +
0.114 * (rgb.b * rgb.b)
);
var circle = d3.select('.answer' + a);
circle.classed('enabled', false);
circle.on('mousedown', null);
if (a == correctIndex) {
circle.classed('yes_' + (hsp > 127.5 ? 'black' : 'white'), true);
} else if (a == index) {
circle.classed('no_' + (hsp > 127.5 ? 'black' : 'white'), true);
}
}
tracker.push(log);
if (tracker.length == levels) {
d3.select('#finish').style('display', 'inline-block');
} else {
d3.select('#next').style('display', 'inline-block');
}
}
function showNewLevel() {
d3.select('#next').style('display', 'none');
var shuffled = colours.slice(0);
shuffleArray(shuffled);
// reroll if we have already had this colour.
// this ensures that at least one colour is new
// and therefore there is always a valid answer
var isValid = true;
do {
isValid = true;
for (var old of tracker) {
if (old.items[old.correctIndex][0] == shuffled[0][0]) {
isValid = false;
}
}
if (!isValid) {
shuffleArray(shuffled);
}
} while (!isValid);
var amount = 6;
// start the answer array with the item that we ensured is a valid answer.
// the array will get shuffled later
answers = [shuffled[0]];
// overwrite if it is a special day
if (fixedAnswers) {
var chosen = shuffled.filter(a => a[0] == fixedAnswers[tracker.length])[0];
answers = [chosen];
}
for (var a = 1; a < shuffled.length; a++) {
var isValid = true;
for (var b = 0; b < answers.length; b++) {
var rgbExisting = hexToRgb(answers[b][1]);
var rgbCandidate = hexToRgb(shuffled[a][1]);
var deltaDiff = deltaE([rgbExisting.r, rgbExisting.g, rgbExisting.b], [rgbCandidate.r, rgbCandidate.g, rgbCandidate.b]);
if (deltaDiff <= minimumDeltaDifference) {
isValid = false;
}
// check if from the same set
if (shuffled[a][3] > 0 && shuffled[a][3] == answers[b][3]) {
isValid = false;
}
}
if (isValid) {
answers.push(shuffled[a]);
}
if (answers.length == amount) {
break;
}
}
if (answers.length < amount) {
showNewLevel();
return;
}
shuffleArray(answers);
var isValid = true;
do {
correctIndex = ~~(rand() * answers.length);
isValid = true;
for (var old of tracker) {
if (old.items[old.correctIndex][0] == answers[correctIndex][0]) {
isValid = false;
}
}
} while (!isValid);
if (fixedAnswers) {
//console.log(answers);
//console.log(fixedAnswers[tracker.length]);
correctIndex = answers.findIndex(a => a[0] == fixedAnswers[tracker.length]);
}
d3.select('#question').html('Which colour is <span class="highlight">' + answers[correctIndex][0] + '?</span>');
d3.selectAll('#answers div').remove();
for (var index in answers) {
var colour = answers[index];
var rgb = hexToRgb(colour[1]);
var hsp = Math.sqrt(
0.299 * (rgb.r * rgb.r) +
0.587 * (rgb.g * rgb.g) +
0.114 * (rgb.b * rgb.b)
);
d3.select('#answers')
.append('div')
.attr('class', 'answer enabled answer' + index)
.attr('data-index', index)
.style('background-color', '#' + colour[1])
.style('color', hsp > 127.5 ? 'black' : 'white')
.html(' ')
.on('mousedown', function () { clickAnswer(d3.select(this).attr('data-index')) });
if (index % 3 == 2) {
d3.select('#answers')
.append('div')
.attr('class', 'mobileBreaker');
}
}
var progress = d3.select('#progress');
var html = '';
for (var a = 0; a < levels; a++) {
if (tracker.length == a) {
html += '◈';
} else if (tracker.length > a) {
html += '◆';
} else {
html += '◇';
}
}
progress.html(html);
}
// see if the user already played this challenge and is remembering results
var savedData = getCookie('db' + daysBetween);
if (savedData && savedData.length == levels) {
hasPlayed = true;
for (var a = 0; a < levels; a++) {
showNewLevel();
clickAnswer(+savedData[a]);
}
showResults();
}
if (!hasPlayed) {
showNewLevel();
}
</script>
</body>
</html>