Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $(document).ready(function() {
- MatchGame.renderCards(MatchGame.generateCardValues(), $('#game'));
- });
- var MatchGame = {};
- /*
- Sets up a new game after HTML document has loaded.
- Renders a 4x4 board of cards.
- */
- /*
- Generates and returns an array of matching card values.
- */
- MatchGame.generateCardValues = function () {
- var ordered = [];
- for(card = 1; card <= 8; card++) {
- ordered.push(card);
- ordered.push(card);
- }
- var random = [];
- while(ordered.length > 0) {
- random.push(ordered.splice(Math.floor(Math.random() * ordered.length), 1));
- }
- return random;
- };
- /*
- Converts card values to jQuery card objects and adds them to the supplied game
- object.
- */
- MatchGame.renderCards = function(cardValues, $game) {
- $game.data('flipped', []);
- var colors = [25,55,90,160,220,265,310,360];
- $game.empty();
- for(i = 0; i < cardValues.length; i++) {
- $e = $("<div class='col-xs-3 card'></div>");
- $e.data('value', cardValues[i]);
- $e.data('flipped', false);
- $e.data('color', 'hsl(' + colors[cardValues[i] - 1] + ', 85%, 65%)');
- $game.append($e);
- }
- $('.card').click(function() {
- MatchGame.flipCard($(this), $('#game'));
- });
- };
- /*
- Flips over a given card and checks to see if two cards are flipped over.
- Updates styles on flipped cards depending whether they are a match or not.
- */
- MatchGame.flipCard = function($card, $game) {
- if($card.data('flipped')) { return }
- $card.data('flipped', true);
- $card.css('background-color', $card.data('color'));
- $card.text($card.data('value'));
- $game.data('flipped').push($card);
- if($game.data('flipped').length == 2) {
- if($game.data('flipped')[0].data('value')[0] == $game.data('flipped')[1].data('value')[0]) {
- $game.data('flipped')[0].css({backgroundColor: 'rgb(153,153,153)', color: 'rgb(204,204,204)'});
- $game.data('flipped')[1].css({backgroundColor: 'rgb(153,153,153)', color: 'rgb(204,204,204)'});
- $game.data('flipped', []);
- } else {
- var card1 = $game.data('flipped')[0];
- var card2 = $game.data('flipped')[1];
- window.setTimeout(function() {
- card1.data('flipped', false);
- card1.text('');
- card1.css('background-color', 'rgb(32, 64, 86)');
- card2.data('flipped', false);
- card2.text('');
- card2.css('background-color', 'rgb(32, 64, 86)');
- }, 350);
- }
- $game.data('flipped', []);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement