In the previous tutorials we have been using the construct "{ x, y }". We are now going to see what this is.
A Point
The Point is a structure type. This is a way of treating a collection of fields as a single object. We will cover how you can create your own types later. The system has a number of built-in structure types, one of which is the Point. The Point is defined to contain three Number fields, named 'x', 'y' and 'z'. The 'z' value defaults to 0 and can be ignored for simple 2D drawings.
It is possible to declare a variable of type Point and treat it either as a single object or you can access each field individually. The syntax for accessing the fields is to use the dot operator '.' followed by the name of the field.
Program( ) Point target; Begin target := { 10, 20 }; Output target; target.x := 30; Output target; End;basic_point_1.grs
This will write the following text to the screen :-
{10, 20, 0} {30, 20, 0}
You can use a Point type variable wherever you can use an explicit pair of values as a coordinate. This includes as a parameter to a shape or as the specified target origin of a shape call. See the following lines of code ( ignore the bits concerning the pens, this will be covered later; just look at the coordinates ) :-
Program( ) Point from = { 10, 10 }, to = { 10, 40 }; Begin Line(from, to) => redpen; LineTo(to) => greenpen; Line({100,100}, {200, 100} ) => from, bluepen; End;basic_point_2.grs
You will notice that Point variables can be initialised when declared just like any other type of variable. If the variable is not initialised both fields will be set to Null. Try the above code and see if you can work out which statement is doing what, and why. Comments out various statements to help.
Functions Returning Points
It is possible to write a function that returns a Point, and as a function call can go anywhere a variable can go, and as Point variable can go anywhere a pair of coordinates can go, so a function call can go anywhere where we require a coordinate pair.
All coordinates in the system are in pixels. I some cases we may want to use out own logical coordinates system. Let us set up a system of cells on the display and we want to draw one of our symbols at the centre of a selected cell.
Program( ) Begin [= . . . other sample calls . . . =] EarthSymbol(10) => CellCentre(2, 3); End; Function Point CellCentre(Number row, Number column) Number size = 50; Number xcoord, ycoord; Point result; Begin xcoord := ( column - 1 ) * size; xcoord := xcoord + size / 2; ycoord := ( row - 1 ) * size ; ycoord := ycoord + size / 2 ; result := { xcoord, ycoord }; Return result; End; [= . . . Symbol Routines . . . =]basic_point_3.grs
The above is a long winded way to go about this. The whole thing can be done in a single statement and without using any variables for intermediate results :-
Function Point CellCentre(Number row, Number column) Number size = 50; Begin Return { ( column - 1/2 ) * size , ( row - 1/2 ) * size }; End;