The constructor and destructor

The first section of code defines the actions to perform when the class instance is loaded (constructor) and unloaded (destructor):

#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include "game.h"

using namespace std;
using namespace Constants;

Game::Game() :
// Create a new random piece:
piece_{ static_cast<Piece::Kind>(rand() % 7) },
moveTime_(SDL_GetTicks())
{
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
throw runtime_error(
"SDL_Init(SDL_INIT_VIDEO): " + string(SDL_GetError()));
}
SDL_CreateWindowAndRenderer(
BoardWidth,
ScreenHeight,
SDL_WINDOW_OPENGL,
&window_,
&renderer_);
SDL_SetWindowPosition(
window_,
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED);
SDL_SetWindowTitle(window_, "Tetris");

if (TTF_Init() != 0) {
throw runtime_error("TTF_Init():" + string(TTF_GetError()));
}
font_ = TTF_OpenFont("PressStart2P.ttf", 18);
if (font_ == nullptr) {
throw runtime_error("TTF_OpenFont: " + string(TTF_GetError()));
}
}

Game::~Game() {
TTF_CloseFont(font_);
TTF_Quit();
SDL_DestroyRenderer(renderer_);
SDL_DestroyWindow(window_);
SDL_Quit();
}

The constructor represents the entry point for the application, so all of the required resources are allocated and initialized within it. The TTF_OpenFont() function is referencing a TrueType font file downloaded from Google Fonts named Press Start 2P. You can view the font at https://fonts.google.com/specimen/Press+Start+2P. It's present in the /resources folder of the repository and gets copied into the same folder as the executable when the project is built. If at any point an error occurs when initializing the SDL2 resources, a runtime_error is thrown with details of the error. The destructor (~Game()) frees up the resources we allocated for SDL2 and SDL2_ttf before the application exits. This is done to avoid a memory leak.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset