Peg Solitaire tutorial

This is an old revision of Peg Solitaire tutorial, edited by Eny at . The current revision is 74923.

/* First steps */

Template:Newpage

This tutorial is the second Lazarus tutorial that aims at introducing the basics of Lazarus application development. It's best to start this tutorial after having finished the first one (Howdy_World_(Hello_World_on_steroids)). This tutorial exlpains a bit about how to work with graphics and how to make a program modular. The final product of this tutorial is a basic but working version of the Peg Solitaire game (http://en.wikipedia.org/wiki/Peg_solitaire). If all goes well in the end it will look something like this:

Start the project

As mentioned in the previous tutorial it's best to start with a clean, separate directory for each project. A quick recap:

And extra for this project:

First steps

It's always a good idea to seperate gui related code from data structure definitions. So the first step will be the creation of a separate unit for our Solitaire data structures.

The basic elements of a Peg Solitaire board are the marbles, the board structure and the empy places. We'll simulate this by a simple matrix that has cells of a certain type (empty, occupied and not accessible). And we'll encapsulate all this in a class that handles all the data manipulation.

<Delphi>const

 C_MAX = 7;  // Max board size: 7x7

type

 TCellNums = 1..C_MAX;
 TCellType = (ctNoAccess, ctEmpty, ctPeg);
 TPegCells = array[TCellNums, TCellNums] of TCellType;
 TPegSolitaire = class
 private
   Size: TCellNums;
   PegCells: TPegCells;
 public
   constructor Create(const pSize: TCellNums);
 end;</Delphi>

It's fair to assume that other code that is going to use this class needs access to the cells contents (i.e. PegCells). The way to handle this is either by defining a set of functions to access the cells or define a so called array property. Let's go for the latter approach and add the following line to the public section of the TPegSolitaire class: <Delphi>property Cell[const pRow, pCol: TCellNums]: TCellType;</Delphi>

<Delphi>result := PegCells[pRow,pCol]</Delphi>

<Delphi>PegCells[pRow,pCol] := pValue</Delphi>

<Delphi>var iRow,iCol: integer; begin

 // Store the size of the board locally
 Size := pSize;
 // Initialize all cells to 'not accessible'
 for iRow := 1 to C_MAX do
   for iCol := 1 to C_MAX do
     Cell[iRow,iCol] := ctNoAccess;</Delphi>

Now that the basic data structure is in place, let's have a look at the graphics we are going to need. There are many ways to display a soliatire board. We are going to use a paintbox. That will give us full control over the graphic features that Lazarus gives us out of the box.

Our main form is going to use the data structure we defined in the PegDatastructure file.

<Delphi>uses

 PegDatastructures,
 Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs;</Delphi>