Creating the Concentration Game PAIRS with Bash


Exploring the nuances of writing a pair-matching memory game and one-dimensional arrays in Bash.

I've always been a fan of Rudyard Kipling. He wrote some great novels and stories, mostly about British colonial-era India. Politically correct in our modern times? Not so much, but still, his books are good fun for readers and still are considered great literature of its time. His works include The Jungle Book, Captains Courageous, The Just So Stories and The Man Who Would Be King, among many others.

He also wrote a great spy novel about a young English boy who is raised as an Indian native and thence recruited by the British government as a spy. The boy's name is the title of the book: Kim. In the story, Kim is trained to have an eidetic memory with a memory game that involves being shown a tray of stones of various shapes, sizes and colors. Then it's hidden, and he has to recite as many patterns as he can recall.

For some reason, that scene has always stuck with me, and I've even tried to teach my children to be situationally aware through similar games like "Close your eyes. Now, what color was the car that just passed us?" Since most of us are terrible observers (see, for example, how conflicting eyewitness accident reports can be), it's undoubtedly good practice for general observations about life.

Although it's tempting to try to duplicate this memory game as a program, the reality is that with just a shell script, it would be difficult. Perhaps you display a random pattern of letters and digits in a grid, then clear the screen, then ask the user to enter patterns, but that's really much more of a game for a screen-oriented, graphical application—not shell scripts.

But, there's a simplified version of this that you can play with a deck of cards: Concentration. You've probably played it yourself at some point in your life. You place the cards face down in a grid and then flip up two at a time to try to find pairs. At the beginning, it's just random guessing, but as the game proceeds, it becomes more about your spatial memory, and by the end, good players know what just about every unflipped card is at the beginning of their turn.

Designing PAIRS

That, of course, you can duplicate as a shell script, and since it is going to be a shell script, you also can make the number of pairs variable. Let's call this game PAIRS.

As a minimum, let's go with four pairs, which should make debugging easy. Since there's no real benefit to duplicating playing card values, it's just as easy to use letters, which means a max of 26 pairs, or 52 slots. Not every value is going to produce a proper spread or grid, but if you aim for 13 per line, players then can play with anywhere from 1–4 lines of possibilities.