Warning

You're browsing the old v2.x documentation. This version is no longer maintained. Click here to go the v3.x documentation.

Step 3.2.1: Finding a shape

The function get_shape() serves to find a shape in the array that we defined in step 2.2. It is rather simple but offers a little trick to make our program run faster. To find a shape in the array, we will use the following formula:

index = shape_no * 4 + rotation

Since each shape has 4 rotations we must multiply the shape number (the number between 0 and 6) by 4 and add the rotation number (which is 0 to 3).

Now the only problem is that function will be called frequently and multiplication is an expensive operation: it takes too long to execute. Luckily, the multiplier is 4, that is a power of two, which means that shifting each bit in the multiplicand two places to the left will give the same result but much faster! So we can code this function as bellow:

FUN get_shape(shape_no!, rotation!)
  RETURN shapes[LSHIFT!(shape_no!, 2) + rotation!]
  
  REM -- Shapes of all pieces in all rotations
  DATA shapes[] = %0100010001000100, %0000111100000000, %0010001000100010, %0000000011110000, ~
                  %0100010011000000, %1000111000000000, %0110010001000000, %0000111000100000, ~
                  %0100010001100000, %0000111010000000, %1100010001000000, %0010111000000000, ~
                  %1100110000000000, %1100110000000000, %1100110000000000, %1100110000000000, ~
                  %0000011011000000, %1000110001000000, %0110110000000000, %0100011000100000, ~
                  %0000111001000000, %0100110001000000, %0100111000000000, %0100011001000000, ~
                  %0000110001100000, %0100110010000000, %1100011000000000, %0010011001000000
ENDFUN

In case this is the first time you write a function in XC=BASIC, you might need to know some important rules:

  • A function always has a return type that is denoted within the function name just like in case of varbiables names. If the function name is not appended with a sigil then it must return an integer. If it is appended with a ! then it must return a byte. % and $ stand for floating point and string pointer types.
  • Functions have their own local scope and they may access global variables using the \ sign prepended to the variable name.
  • Functions must return a value. If a function ends without a RETURN statement, a compile-time error will be emitted.
  • Functions can't be recursive (although procedures can).

If they're something new to you, chek out the LSHIFT and RSHIFT functions that shift the bits of the operand to the left or right.

Note that I have moved the DATA statement previously added to the program here inside this function because this is the only place where it will be used and therefore it is logical to place it here.

Let's go on, we still have a lot more to do.