-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
61 lines (50 loc) · 1.42 KB
/
game.js
File metadata and controls
61 lines (50 loc) · 1.42 KB
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
$(document).ready(function() {
var num_tiles = 16;
var tiles = [];
for (var i = 0; i < num_tiles / 2; i++) {
var $tile = $("<li></li>");
$tile.html(i);
$tile.addClass("tile");
tiles.push($tile);
}
for (var i = 0; i < num_tiles / 2; i++) {
var $tile = $("<li></li>");
$tile.html(i);
$tile.addClass("tile");
tiles.push($tile);
}
var shuffle = function(arr) {
for (var i = 0; i < arr.length; i++) {
var j = Math.floor(Math.random() * i);
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
};
var shuffled_tiles = shuffle(tiles);
for (var i=0; i < tiles.length; i++) {
$("#game-board").append(shuffled_tiles[i]);
}
var $first_clicked_tile, $second_clicked_tile;
var pairs = 0;
$(".tile").click(function() {
if(!$first_clicked_tile) {
$first_clicked_tile = $(this);
$(this).addClass("selected");
} else {
$second_clicked_tile = $(this);
}
if ($first_clicked_tile.html() === $second_clicked_tile.html()) {
$second_clicked_tile.addClass('selected');
pairs++;
} else {
$first_clicked_tile.removeClass('selected');
}
$first_clicked_tile = null;
$second_clicked_tile = null;
if(pairs === num_tiles / 2 ) {
alert('You won!');
}
});
});