How to Code a Game of Solitaire

This is Part 2 of my how to program a data driven game of Patience development blog.

Now, as I'm sure that you know, there are many different types of Solitaire, and many different card layouts used for the games.

Although I'm keen to have as many varieties of Solitare as possible on my solitaire site, it's important not to overcomplicate when you start coding. In industry, there exists the idea of the MVP (Minimum Viable Product), which is a piece of software that will do the essentials and nothing more.

You get this working as fast as possible, iterate and add features.

I'm doing the same with SolitaireOnline.Org. I'm writing an MVP, which I will improve upon over time.

For a Minimum Viable Product you have to decide on what you absolutely *must* include and nothing else.

SolitaireOnline.Org is data driven. This means that I need more than one game of Patience from the outset, to ensure that my data structures are not too specific for a one type of Patience only.

The initial games (definitely Klondike, Pyramid and Clock Solitaire). The layouts are sufficiently different that they should test my generic screen drawing routine. I hope.

They will only use one pack of cards, with card layouts which take up a maximum screen layout of nine cards horizontally by seven vertically.

It is easiest to think of this by imagining a table, and then picking up an imaginary deck of cards. Lay nine cards down horizontally, move down a row and repeat seven times.

This isn't enough for all of the many types of Patience. It is enough for an MVP, and to get started.

The Card Layout

As alluded to in my previous entry, The Initial Setup, laying out the deck of cards is fiddly. The code needs to take into account different screen resolutions, phones, laptops and pads of differing sorts.

It also needs to handle rotation, as a phone screen rotates from landscape to portrait.

It took me several attempts to come up with a robust way of handling this in code. If you are reading this and planning on implementing a game of patience, it might save you some time.

There may well be a better method to do this, but after a lot of faffing, I settled on using a grid layout, which works as follows.

When the game starts, the screen is resized or rotated, a function named setGridPositionsAndCardSize() is called.

In essence, setGridPositionsAndCardSize calculates and saves the positions of an imaginary grid overlaid on the phone screen. If you magine a large piece of graph paper, and on each intersection placing a card. You can rotate this from portrait to landscape and back, and each time calculate the points exactly.

This function also calculates the dimensions of the cards. These will change if the screen is rotated or the size of the screen is changed.