17.1.2 Create and Draw

The Create method of square is rather straightforward. You have to make sure the arguments are stored in the class variables. Complete this method on your own.

Slightly more difficult is the draw function. Let’s sum up what this method should do.

  1. Depending on the BLOCK_TYPE, a color should be set.
  2. The position of the square is the position in the grid. We need to calculate the actual position on the screen.
  3. We have to show an image on the screen, at the calculated position.

The color will be determined with a switch statement. We declare a variable of the type Color and assign the value BLACK. Next, this is changed to the desired color for each type:

 
Color color(BLACK); 
 
switch(type) 
{ 
5   case BT_SQUARE     : color = RED   ; break
   case BT_T          : color = PURPLE; break
   case BT_L          : color = GREY  ; break
   case BT_BACKWARDS_L: color = BLUE  ; break
   case BT_STRAIGHT   : color = GREEN ; break
10   case BT_S          : color = PINK  ; break
   case BT_BACKWARDS_S: color = YELLOW; break
   case BT_BACKGROUND : color = Color(50, 50, 50) ; break
   case BT_WALL       : color = WHITE ; break
}  
15

Next we have to determine the position. The constant GAMEAREA is the lower left corner of the playing field. All positions are calculated from that point. The bottom left corner of the square at the position (0,0) would therefore have to be equal to the lower left corner of the playing field. Therefore:

 
Vec2 screenpos = GAMEAREA;  

Suppose you want a square at position (1,0). The bottom left corner of the square is equal to that of the playing field, plus the width of one square. For all other positions, the same applies: you multiply the grid position with the size of the square:

 
Vec2 screenpos = GAMEAREA + (pos * SQUARE_SIZE);  

The upper right corner of the square is exactly one square further. We can create a rectangle to draw on the screen in the following way:

 
Vec2 screenpos = GAMEAREA + (pos * SQUARE_SIZE); 
Rect r(screenpos, screenpos + SQUARE_SIZE);  

To draw the actual image on the screen, use the following code:

 
Images(=== tetris square ===).draw(color, TRANSPARENT, r);