Concentration is an old card game ideally suited as a computer program. Instead of cards, I use photos. The game is a pure memory skills test.

Six pairs of photos are hidden behind squares. The player uncovers two squares at a time. If they match, they remain uncovered. If not, they become hidden again. The goal is to commit the photo’s location to memory so that when a new square is uncovered its pair can be found. Find all pairs using as few guesses as possible.

Like Mastermind and Hangman, Concentration was written in JavaScript, and designed to scale for any display, from large desktops to small mobile devices. I recycled much of the same code from those other programs (see Building Mastermind for All Screen Sizes and Creating Hangman in JavaScript). The layout is determined dynamically at start-up and when the window is resized.

I don’t like scaling images, at least not in HTML, so instead each photo uses one of the 3 standard sizes from Flickr: square (75×75), thumbnail (no larger than 100×100), and small (no larger than 240×240). As the window is resized, the spacing between images will adjust, until the constraints call for a change of image size. I also dynamically determine the number of rows and columns. Given an area width × height pixels, objects can be arranged using the formula:

columns = Math.sqrt(N*width/height)
rows = N/columns;

To ensure whole numbers, I round columns down to 12, 6, 4, 3, 2 or 1 (given N = 12).

For the sake of simplicity, I use the onClick event only on the black squares, not the images below them. To reveal an image, I change the backgroundColor from black to “transparent.” Unlike changing an element’s visibility property to hidden, changing the color to transparent doesn’t change its clickability, even if the user can’t see the element. The question mark is turned into a or (or erased) by changing the innerHTML and color properties.

You can play the game at mvjantzen.com/games/concentration.php.

JavaScript Concentration Game

Leave a Reply