forked from sismoon2013/js-flip-and-match-game
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.html
557 lines (518 loc) · 15.7 KB
/
game.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
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Yet another web experiement by Rajendra Patil. Was an assignment to me and I completed the same in few hours.">
<meta name="keywords" content="HTML5,CSS3,JavaScript, Game">
<meta name="author" content="Rajendra Patil <[email protected]>">
<meta charset="utf-8" />
<title>Simple Guessing Game</title>
<style>
body {
background: #ddd;
margin: 0 auto;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.letter {
font-size: 150px;
}
.title {
font: 38px bold;
text-align: center;
padding: 10px;
}
.layout {
border: 1px solid #bbb;
margin: auto;
-moz-box-shadow: 8px 8px 5px gray;
box-shadow: 8px 8px 5px gray;
background: #fff;
max-width: 824px;
white-space: nowrap;
padding: 30px;
}
.hidden {
visibility: hidden;
}
.message {
text-align: center;
width: 60%;
margin: auto;
border: 1px solid gray;
padding: 5px;
background: #ffd;
-moz-border-radius: 20px;
border-radius: 20px;
}
.grid {
-moz-perspective: 800;
-o-perspective: 800;
-webkit-perspective: 800;
position: relative;
margin: 20px auto 20px 10px;
}
.tile {
margin: 10px;
width: 175px;
height: 175px;
border: 1px solid silver;
float: left;
}
.tile .front, .tile.flipped .back {
visibility: visible;
}
.tile.flipped .front, .tile .back {
visibility: hidden;
}
.clear {
clear: both;
}
.tile.flipped {
-moz-transform: rotatey(-180deg);
-o-transform: rotateY(-180deg);
-webkit-transform: rotatey(-180deg);
-moz-box-shadow: -8px 8px 5px gray;
box-shadow: -8px 8px 5px gray;
}
.tile {
-moz-transform-style: preserve-3d;
-o-transform-style: preserve-3d;
-webkit-transform-style: preserve-3d;
-moz-transition: 0.5s;
-o-transition-duration: 0.5s;
-webkit-transition: 0.5s;
}
.tile .face {
position: absolute;
-moz-backface-visibility: hidden;
-o-backface-visibility: hidden;
-webkit-backface-visibility: hidden;
z-index: 2;
text-align: center;
width: 175px;
height: 175px;
}
.tile .front {
position: absolute;
z-index: 1;
cursor: pointer;
background-color: #54B3B3;
}
.tile .back {
-moz-transform: rotatey(-180deg);
-o-transform: rotateY(-180deg);
-webkit-transform: rotatey(-180deg);
background: #eee;
color: black;
cursor: pointer;
}
.tile .phrase {
display: none;
margin-top: 40%;
font: 18px bold;
white-space: normal;
}
.tile.matched {
border-color: #ddd;
-moz-box-shadow: none;
box-shadow: none;
}
/*.tile.matched .phrase {
display: block;
}*/
.tile.matched img {
display: none;
}
.msg_box {
width: 100%;
margin: 10px auto;
border: 1px solid silver;
width: 300px;
padding: 10px;
font-size: 20px;
background: #ddd;
-moz-box-shadow: 8px 8px 5px gray;
box-shadow: 8px 8px 5px gray;
}
.msg_box .icon {
display: inline-block;
zoom: 1;
*display: inline;
-moz-border-radius: 20px;
border-radius: 20px;
background: #ffd;
color: green;
width: 20px;
padding: 6px 8px;
border: 1px solid #ccc;
font-weight: bold;
}
.msg_box .play_again {
text-align: center;
padding: 10px;
margin-top: 30px;
}
.msg_box input {
background: #eee;
padding: 5px;
font-weight: bold;
}
</style>
</head>
<body>
<div class="layout">
<div class="title">Guessing Game - HTML(5), CSS3, JS</div>
<div id="msg_div_top" class="message"></div>
<div id="grid" class="grid"></div>
<div id="msg_div_bottom" class="message"></div>
</div>
<script>
//My own tiny library :) - Inspired by underscore.js
var $ = function(id) {
return document.getElementById(id);
};
//To check if object is an array
var $isArray = function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
//Loop on each element of map or array
var $each = function(obj, callback) {
if ($isArray(obj)) {
for (var idx = 0, len = obj.length; idx < len; idx++) {
callback(obj[idx], idx);
}
} else {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
callback(obj[key], key);
}
}
}
};
//Simple templating
var $template = function(str, data) {
if (!data) return str;
return str.replace(/<%=(\w+)%>/img, function(match, p1) {
return data[p1];
})
};
//Simple AjaxLoader
var AjaxLoader = function() {
if (typeof XMLHttpRequest == "undefined")
XMLHttpRequest = function () {
try {
return new ActiveXObject("Msxml2.XMLHTTP.6.0");
}
catch (e) {
}
try {
return new ActiveXObject("Msxml2.XMLHTTP.3.0");
}
catch (e) {
}
try {
return new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
throw new Error("Browser doesn't support XMLHttpRequest");
};
return {
load: function(url, callback, headers) {
var xhr = new XMLHttpRequest();
if (headers) {
$each(headers, function(value, key) {
xhr.setRequestHeader(key, value);
});
}
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
callback.exec ? callback.exec(xhr) : callback(xhr);
}
}
};
xhr.send(null);
}
}
}();
//Simple callback - executable function
var Callback = function(func, context) {
this.exec = function(data) {
context ? func.call(context, data) : func(data);
}
};
//Simple Inheritance
var Extend = function(Child, Parent, prototypes) {
Child.prototype = new Parent();
Child.prototype.constructor = Parent;
$each(prototypes, function(value, key) {
Child.prototype[key] = value;
})
};
var Utils = {
//Finds random
getRandom: function(start, end) {
return Math.floor(Math.random() * (end - start + 1) + start);
}
};
//Global UI objects list
var _registry = {};
_count = 1;
var UIObject = function() {
};
//To call a UIObject method from the dom event
UIObject.domEvent = function(id, name) {
var comp = _registry[id];
var args = Array.prototype.slice.call(arguments).splice(0, 2); //remove id and name
comp && comp[name] && comp[name].apply(comp, args);
};
//UIOBject extnds Object
Extend(UIObject, Object, {
//Add to UIObject's registry
_init: function() {
this.id = _count++;
_registry[this.id] = this;
this._listeners = {};
},
_destroy : function() {
delete _registry[this.id];
},
//Simple event subscription
listen: function(eventName, callback) {
this._listeners[eventName] = this._listeners[eventName] || [];
this._listeners[eventName].push(callback);
},
//Simple event notificaton
notify: function(eventName, data) {
var listeners = this._listeners[eventName];
if (listeners) {
var me = this;
$each(listeners, function(callback) {
data.object = me; //the one who is notifying
callback.exec(data);
});
}
}
});
//Tile is our UIObject
var Tile = function(letter, phrase) { //Constructor
this._letter = letter;
this._phrase = phrase;
this._init();
};
//Template
Tile.TMPL = '<div onclick="UIObject.domEvent(<%=id%>,\'flip\');" class="tile" id="<%=id%>"><div class="face front"> </div> \
<div class="face back"><div class="letter" id="<%=id%>_letter" height="175" width="175"><%=letter%></div> \
<div class="phrase"><%=phrase%></div> \
</div></div>';
//Event
Tile.EVENT_STATE_CHANGED = "STATE_CHANGED";
//Tile extends UIObject
Extend(Tile, UIObject, {
//Eval's template, fill the data and returns the HTML
getHtml: function() {
return $template(Tile.TMPL, {id:this.id, letter: this._letter, phrase: this._phrase});
},
isFlipped: function() {
return this._flipped;
},
//Flip or unflip it
flip: function() {
if (this._matched) return;
if (this._flipped) {
return this.unFlip();
}
/*var img = $(this.id + "_img");
var src = img && img.getAttribute("thesrc"); //lazy load images - on demand
if (src) {
img.src = src;
img.removeAttribute("thesrc");
}*/
var dom = $(this.id);
if (dom) {
dom.className = "tile flipped";
}
this._flipped = true;
this.notify(Tile.EVENT_STATE_CHANGED, {flipped: true});
},
//Unflip
unFlip: function() {
var dom = $(this.id);
if (dom) {
dom.className = "tile";
}
this._flipped = false;
this.notify(Tile.EVENT_STATE_CHANGED, {flipped: false});
},
//Mark as matched
markMatched: function() {
var dom = $(this.id);
if (dom) {
dom.className = "tile flipped matched";
dom.onclick = null;
}
this._matched = true;
this.notify(Tile.EVENT_STATE_CHANGED, {matched: true});
},
//Compare with another tile
equals: function(tile) {
return tile instanceof Tile && tile.id != this.id && this._letter.toLowerCase() === tile._letter.toLowerCase() && this._phrase === tile._phrase;
},
//reset the state
reset: function() {
this.unFlip();
this._matched = false;
}
});
// GuessingGame is a UIObject again
var GuessingGame = function(data, gridContainer) { //constructor
this._data = data;
this._gridContainer = gridContainer;
this._tiles = [];
this._matchCount = 0;
this._current = null;
this._init();
this.init();
};
//Success dialog TMPL
GuessingGame.DIALOG_TMPL = '<div id="success" class="msg_box"> \
<div><div class="icon">✓</div> Good job! </div> \
<div class="play_again"><input id="play_again_btn" \
type="button" value="Play again" onclick="play_a_game()"/></div> \
</div>';
//Extends UIObject
Extend(GuessingGame, UIObject, {
_setMessage: function(dom, message) {
if (dom) {
if (message) {
dom.innerHTML = message;
dom.className = "message";
} else {
dom.innerHTML = " ";
dom.className = "message hidden";
}
}
},
//Reshuffles the tiles
_reshuffle: function() {
this._matchCount = 0;
this._current = null;
var reshuffled = [];
var start = 0;
var end = this._tiles.length - 1;
var me = this;
$each(this._tiles, function(tile) {
tile.reset();
var random = Utils.getRandom(start, end);
while (reshuffled[random]) { //already taken, find next
random = Utils.getRandom(start, end);
}
reshuffled[random] = tile;
});
this._tiles = reshuffled;
},
//Create a tile for the given item
_createTile: function(letter) {
var tile = new Tile(letter, "");//, item.phrase);
tile.listen(Tile.EVENT_STATE_CHANGED, new Callback(this.tileStateChanged, this));
return tile;
},
showMessage: function(message) {
this._setMessage($("msg_div_top"), message);
this._setMessage($("msg_div_bottom"), message);
},
showSuccessDialog: function(message) {
//this._setMessage($("msg_div_top"));
//this._setMessage($("msg_div_bottom"));
var dom = $("msg_div_top");
if (dom) {
dom.innerHTML = $template(GuessingGame.DIALOG_TMPL, {id: this.id});
}
},
//Checks if the tiles do match, unflip otherwise
compareAndCheck: function(data) {
var tile = data.object;
if (data.flipped) { //Flipped
if (!this._current) { //No previous flipped tile, set this then
this._current = tile;
} else if (this._current.equals(tile)) { //This flip matches with previous one
this._current.markMatched();
tile.markMatched();
this._current = null;
this.showMessage("Removed matching tiles!");
this._matchCount += 2;
if (this._matchCount === this._tiles.length) {
//showMessage("You won!");
this.showSuccessDialog();
}
} else { //Tiles do not match, unflip both of them
this._current.unFlip();
tile.unFlip();
this._current = null;
this.showMessage("Tiles do not match!");
}
}
},
//Tile state change listener (callback)
tileStateChanged: function(data) {
var tile = data.object;
this.showMessage();
if (data.flipped) {
if (!this._current) {
this._current = tile;
} else {
var me = this;
setTimeout(function() {
me.compareAndCheck(data);
}, 750);
}
} else {
this._current = null;
}
},
//Init tiles from the data
init: function() {
var me = this;
$each(this._data, function(item) {
//2 tiles for 1 item
me._tiles.push(me._createTile(item.letter));
me._tiles.push(me._createTile(item.letter.toLowerCase()));
});
},
//Play - reshuffle, and rerender the tiles
start: function() {
this._reshuffle();
this.showMessage("Find matching tiles as quickly as you can!");
var gridDom = $(this._gridContainer);
if (gridDom) {
var html = [];
$each(this._tiles, function(tile) {
html.push(tile.getHtml());
});
html.push('<div class="clear"></div>');
gridDom.innerHTML = html.join("");
}
}
});
var play_a_game = function() {
var CHAR_A = 65,
count = 6,
myGame,
letters = [],
start = (Utils.getRandom(count, 25) - count);
while (count) {
letters.push({letter:String.fromCharCode(CHAR_A + start + count--)});
}
myGame = new GuessingGame(letters, "grid");
myGame.start();
};
play_a_game();
</script>
</body>
</html>