Using Arrays in Smart Pascal
IntroductionWe have covered the data types integer, string, real and Boolean. An array is a data structure used to store data items of the same type. In a static array, the array has a fixed length that is included in the declaration. A dynamic array is declared without a length. Its length must be set before use, and the length can be changed to suit changing circumstances. We begin with static arrays, which are easier to use.
var Colours : array [1 .. 6] of string;
Array declarations must show the identifier (in this case Colours), the bounds (a start value of 1 and an end value of 6) and the type (string).
Colours := 'pink';uses the index 2 to assign the value 'pink' to the second string in the array. The statement
Canvas.FillStyle := Colours;would then set the fill colour to pink.
var Colours : array [1 .. 6] of string = ['red', 'pink', 'white', 'black', 'blue', 'green'];
This short demonstration randomly chooses each second a colour for the GameView.
unit Unit1; interface uses System.Types, SmartCL.System, SmartCL.Components, SmartCL.Application, SmartCL.Game, SmartCL.GameApp, SmartCL.Graphics; type TCanvasProject = class(TW3CustomGameApplication) protected procedure ApplicationStarting; override; procedure ApplicationClosing; override; procedure PaintView(Canvas: TW3Canvas); override; end; implementation var Colours : array [1 .. 6] of string = ['red', 'pink', 'white', 'black', 'blue', 'green']; procedure TCanvasProject.ApplicationStarting; begin inherited; GameView.Delay := 1000; GameView.StartSession(True); end; procedure TCanvasProject.ApplicationClosing; begin GameView.EndSession; inherited; end; procedure TCanvasProject.PaintView(Canvas: TW3Canvas); begin // Clear background to one of six colours chosen at random var i := RandomInt(6) + 1; Canvas.FillStyle := Colours[i]; Canvas.FillRectF(0, 0, GameView.Width, GameView.Height); end; end.
var Alien_X_Coords: array[1 .. 100] of integer;You could use this array to store successive x coordinates for an alien to take as it wanders down the screen.
The demonstration on the following page uses the LandHeight array to store a randomly generated terrain to be used in a game. The code is based on Jason McMillen's Artillery.
private TrackCoords: array [1..227, 1..2] of integer;The first x and y coordinates would then be assigned with the code:
TrackCoords[1, 1] := 1300; TrackCoords[1, 2] := 300;You can see how much more laborious it would be to assign values individually!
LandHeight: array of integer;
A dynamic array is zero-based and has useful "pseudo-methods" such as Push (to add an element to the end), Pop (to remove the last element), Clear, Copy, Delete, IndexOf, Swap and Reverse.