SitePoint Code Challenge: Javascript – A Game of Memory

Sarah Hawk
Tweet

Here is part 2 of yesterday’s CSS challenge. The CSS gurus in our community have been challenged to style and animate the cards of a game of Memory, and this challenge is to adjudicate the game.

Here’s the HTML we are working from:

<!DOCTYPE html>
<html>
<head>
  <title>Memory</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  <script type="text/javascript">
    $('.card').click(function(){
	  $(this).toggleClass('down');
	});
  </script>
</head>
<body>
  <div id="Playfield">
    <div data-face="1"></div>
    <div data-face="2"></div>
    <div data-face="3"></div>
    <div data-face="4"></div>
    <div data-face="5"></div>
    <div data-face="6"></div>
    <div data-face="7"></div>
    <div data-face="8"></div>
    <div data-face="9"></div>
    <div data-face="10"></div>
    <div data-face="11"></div>
    <div data-face="12"></div>
    <div data-face="1"></div>
    <div data-face="2"></div>
    <div data-face="3"></div>
    <div data-face="4"></div>
    <div data-face="5"></div>
    <div data-face="6"></div>
    <div data-face="7"></div>
    <div data-face="8"></div>
    <div data-face="9"></div>
    <div data-face="10"></div>
    <div data-face="11"></div>
    <div data-face="12"></div>
  </div>
</body>
</html>

Yesterday we provided the CSSers enough JS to test their styling – toggling the classes of the cards. Here’s the rest of the challenge, and most of its logic can be tied into the click event above.

The cards are in pairs, their last class name reveals the matching.

When a card is clicked, a check needs to be made to see if any other cards are face up that do not have the CSS class ‘matched’. If there is, does the value of the data-face attribute of the two cards match? If so, the two cards gain the css class of ‘matched’, otherwise turn both face down.

You also need to test when all cards are matched to give a ‘You Win’ result.

Advanced
Shuffle the position of the cards. You can do this a number of ways – but if you choose the changing of the data-face value make sure you change the corresponding css class because that’s how the styling is going to give the card it’s particular image.

Expert
Make a two player game and keep score.

At all levels you may add to the HTML to give additional controls, like a reset game or shuffle button, but don’t remove anything or you risk breaking the style sheets being written for the challenge.

A solution will be given in this thread in the coming days.

Happy coding!

Thanks for Michael Morris for designing this challenge.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments