Сегодня мы создадим простую традиционную игру Memory с помощью jQuery. В этой игре реализация функционала будет только на стороне клиента.
Напомним правила. Игрок наугад открывает пары карточек, если изображение у пары совпадает, то эти карточки остаются раскрытыми. Цель игры — раскрыть все карточки за наименьшее количество кликов.
Пример Скачать (.zip, 303 Кб)
HTML
В этом примере используются 20 карточек с 10 уникальными изображениями, но в коде, расположенном ниже, мы покажем вам структуру HTML, используя всего 3 изображения, чтобы сократить код. Кроме того, в HTML каркас добавим кнопки сброса, скачивания и перехода к статье, а также, счетчик кликов.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<div id="boxbutton"><span> <span id="count">0</span> Click </span> <a onclick="resetGame();" href="javascript:">Reset</a></div> <div id="boxcard"> <div id="card1"><img src="img/01.jpg" alt="" /></div> <div id="card2"><img src="img/02.jpg" alt="" /></div> <div id="card3"><img src="img/03.jpg" alt="" /></div> <div id="card11"><img src="img/01.jpg" alt="" /></div> <div id="card12"><img src="img/02.jpg" alt="" /></div> <div id="card13"><img src="img/03.jpg" alt="" /></div> </div> |
jQuery
Для перетасовки изображений будем использовать функцию shuffle images, кроме того, добавим функционал сброса игры и подсчета кликов, которые сделал игрок.
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 |
var boxopened = ""; var imgopened = ""; var count = 0; var found = 0; function randomFromTo(from, to){ return Math.floor(Math.random() * (to - from + 1) + from); } function shuffle() { var children = $("#boxcard").children(); var child = $("#boxcard div:first-child"); var array_img = new Array(); for (i=0; i array_img[i] = $("#"+child.attr("id")+" img").attr("src"); child = child.next(); } var child = $("#boxcard div:first-child"); for (z=0; z randIndex = randomFromTo(0, array_img.length - 1); // установка нового изображения $("#"+child.attr("id")+" img").attr("src", array_img[randIndex]); array_img.splice(randIndex, 1); child = child.next(); } } function resetGame() { shuffle(); $("img").hide(); $("img").removeClass("opacity"); count = 0; $("#msg").remove(); $("#count").html("" + count); boxopened = ""; imgopened = ""; found = 0; return false; } $(document).ready(function() { $("img").hide(); $("#boxcard div").click(openCard); shuffle(); function openCard() { id = $(this).attr("id"); if ($("#"+id+" img").is(":hidden")) { $("#boxcard div").unbind("click", openCard); $("#"+id+" img").slideDown('fast'); if (imgopened == "") { boxopened = id; imgopened = $("#"+id+" img").attr("src"); setTimeout(function() { $("#boxcard div").bind("click", openCard) }, 300); } else { currentopened = $("#"+id+" img").attr("src"); if (imgopened != currentopened) { // снова закрываем setTimeout(function() { $("#"+id+" img").slideUp('fast'); $("#"+boxopened+" img").slideUp('fast'); boxopened = ""; imgopened = ""; }, 400); } else { // найдено $("#"+id+" img").addClass("opacity"); $("#"+boxopened+" img").addClass("opacity"); found++; boxopened = ""; imgopened = ""; } setTimeout(function() { $("#boxcard div").bind("click", openCard) }, 400); } count++; $("#count").html("" + count); if (found == 10) { msg = '<span id="msg">Congrats ! You Found All Sushi With </span>'; $("span.link").prepend(msg); } } } }); |
После открытия карточки срабатывает некоторая пауза, чтобы игрок успел запомнить изображение на ней, вдобавок к этому убираются события клика со всех остальных карточек, чтобы пользователь случайно на них не нажал.
CSS
При раскрытии пары одинаковых изображений, к ним добавляется дополнительное CSS свойство, чтобы выделить уже открытые карточки от открываемых. В данном случае, открытые карточки будут полупрозрачны на 40%.
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 |
#boxcard { margin: 0 auto; width: 625px; z-index: 1; } #boxcard div { float: left; width: 100px; height: 100px; background: #d9d9d9; margin: 5px; padding: 5px; border: 1px solid #999; cursor: pointer; -webkit-border-radius: .5em; -moz-border-radius: .5em; border-radius: .5em; -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.5); -moz-box-shadow: 0 1px 2px rgba(0,0,0,.5); box-shadow: 0 1px 2px rgba(0,0,0,.5); z-index: 2; } #boxcard div img { border: none; z-index: 3; } .opacity { opacity: .6; filter: alpha(opacity=60); } |