#MonthOfCode - Day 12: pixel

My entry for the 12th day of the month of code. The theme for today is: pixel.

Again, this is a little game. This time, you need to find and click the different pixel as quickly as possible.

Click to start:

Code after the break.

pixel.jsview raw
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
document.addEventListener('DOMContentLoaded', function() {
var $el = $('#moc-12');
var $pixel = $('#pixel-12');
var intervalId;
var started = false;
var startTime;
var i = -1;
var x, y;
var pixels = [{
pixel : 'white',
background : 'black'
}, {
pixel : 'green',
background : 'blue'
}, {
pixel : 'yellow',
background : 'orange'
}, {
pixel : 'red',
background : 'pink'
}, {
pixel : '#11F1CD',
background : '#27C064'
}];

$el.on('click', function (ev) {
if (!started) {
started = true;
startTime = Date.now();
nextPixel();
} else {
var dx = ev.offsetX - x;
var dy = ev.offsetY - y;
if (dx*dx+dy*dy < 20) {
nextPixel();
}
}
})

function nextPixel() {
i++;
if (i >= pixels.length) {
end();
return;
}
var p = pixels[i];
x = rand(10, 390);
y = rand(10, 290);

$el.css({
'background-color': p.background
});
$pixel.css({
'background-color': p.pixel,
'top': y,
'left': x
});
}

function formatTime(time) {
var s = Math.floor(time/1000);
var ms = time - s * 1000;
ms = ('00' + ms).slice(-3);
return s + '.' + ms[0];
}

function end() {
var time = formatTime(Date.now() - startTime);
alert("You did it in " + time + " seconds. Reload the page to play again");
}

function rand(min, max) {
return min + Math.floor(Math.random() * (max - min));
}
});