16.2 Constants

In the previous chapter you learned about constants. It is a good idea to create some important constants before you start on the actual code. You can use them anywhere in your code and easily adjust their values if necessary. Create a new code file ‘constants’ in the folder ‘Tetris parts/definitions’.

To be able to change the name of the app later on, create a constant Str with a provisional name.

 
Str APP_NAME = ”Tetris”;  

The size of the standard application window is not ideal for this game. A size in pixels is required for this. Declare a constant int for this purpose.

 
// The window size on the screen, in pixels 
int WINDOW_WIDTH  = 900; 
int WINDOW_HEIGHT = 800;  

Tetris consists of rows and columns. we also define these:

 
// This impacts the playing field 
int SQUARES_PER_ROW = 10; 
int ROWS            = 15;  

It is also possible to add a few constants for the scoring system. There is a fixed number of levels, and we know how much points will be rewarded for a line and a level.

 
// The scoring system uses these 
int POINTS_PER_LINE  =  525; 
int POINTS_PER_LEVEL = 6300; 
int NUM_LEVELS       =    5;  
5

The speed of the game goes up with each level. This change can also be defined as a constant.

 
// The speed will increase every level 
float INITIAL_SPEED = 1.0; 
float SPEED_CHANGE  = 0.1;  

When playing tetris, there is a short period after moving a block down in which you are able to move it sidewards. This period has to be defined.

 
// The time a block can be slided to the side 
// When it hits bottom 
float SLIDE_TIME = 0.25;  

We also have to determine the size of the playing field. This is done by defining the position of the lower left corner, and defining the size of the rectangle containing the playing field.

 
// The area reserved for the playing field 
Vec2 GAMEAREA     (-0.8, -0.8); 
Vec2 GAMEAREA_SIZE( 1.0,  1.4);  

A new block will always appear at the top of the screen. This position can be deducted from information we already have: SQUARES_PER_ROW and ROWS. In addition, there is a waiting position, top right of the playing field. You might notice we are not using Vec2, but VecI2. This is a vector which fits only integers. We do not want Tetris blocks midway between two positions, so there is no need for floats here.

 
// Position for the current and next block 
C VecI2 STARTPOS(SQUARES_PER_ROW / 2, ROWS - 1); 
C VecI2 WAITPOS (SQUARES_PER_ROW + 4, ROWS - 3);  

Now it is possible to calculate the size of a square with the information we already have. This has the advantage that we can modify the foregoing constants later, the size of a square being automatically adjusted.

 
// The size of a square 
float SQUARE_SIZE = GAMEAREA_SIZE.x / SQUARES_PER_ROW;  

Note
Of course it will rarely happen that you precisely know which constants are needed when you’re just starting out on a project. In practice you will usually add a lot of constants while you are working on your project.