The loop() function

The final section of code represents the Game::loop:

bool Game::loop() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_KEYDOWN:
handleKeyEvents(event);
break;
case SDL_QUIT:
return false;
default:
return true;
}
}

SDL_SetRenderDrawColor(renderer_, /* Dark Gray: */ 58, 58, 58, 255);
SDL_RenderClear(renderer_);
board_.draw(renderer_, font_);
piece_.draw(renderer_);

if (SDL_GetTicks() > moveTime_) {
moveTime_ += 1000;
Piece newPiece = piece_;
newPiece.move(0, 1);
checkForCollision(newPiece);
}
SDL_RenderPresent(renderer_);
return true;
}

void Game::checkForCollision(const Piece &newPiece) {
if (board_.isCollision(newPiece)) {
board_.unite(piece_);
piece_ = Piece{ static_cast<Piece::Kind>(rand() % 7) };
if (board_.isCollision(piece_)) board_ = Board();
} else {
piece_ = newPiece;
}
}

void Game::handleKeyEvents(SDL_Event &event) {
Piece newPiece = piece_;
switch (event.key.keysym.sym) {
case SDLK_DOWN:
newPiece.move(0, 1);
break;
case SDLK_RIGHT:
newPiece.move(1, 0);
break;
case SDLK_LEFT:
newPiece.move(-1, 0);
break;
case SDLK_UP:
newPiece.rotate();
break;
default:
break;
}
if (!board_.isCollision(newPiece)) piece_ = newPiece;
}

The loop() function returns a Boolean as long as the SDL_QUIT event hasn't fired. Every 1 second, the draw() functions for the Piece and Board instances are executed, and the piece locations on the board are updated accordingly. The left, right, and down arrow keys control the piece's movement while the up arrow key rotates the piece by 90 degrees. Appropriate responses to key presses are handled in the handleKeyEvents() function. The checkForCollision() function determines if a new instance of the active piece collided with either side of the board or came to rest on top of the other pieces. If it did, a new piece is created. The logic for clearing the rows (via the unite() function of Board) is also handled in this function. We're almost done! Let's move on to the main.cpp file.

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

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