#include "block.h" #include #include extern SDL_Surface *loadImg(std::string filename); extern void drawSurface(int x, int y, SDL_Surface *src, SDL_Surface *dest); Block::Block(std::string filename) { blockImg = loadImg(filename); x = y = type = 0; srand(time(NULL)); } Block::~Block() { SDL_FreeSurface(blockImg); } /* These are the shapes the blocks can be arranged in as they fall. Line: * * * L: * * ** SQUARE: ** ** EVIL: * * * * * */ const int Block::SIZE = 25; const int Block::LINE = 0; const int Block::SQUARE = 1; const int Block::L = 2; const int Block::EVIL = 3; const int Block::line[3][3] = {{0, 1, 0}, {0, 1, 0}, {0, 1, 0}}; const int Block::l[3][3] = {{0, 1, 0}, {0, 1, 0}, {0, 1, 1}}; const int Block::square[3][3] = {{0, 0, 0}, {1, 1, 0}, {1, 1, 0}}; const int Block::evil[3][3] = {{1, 0, 1}, {0, 1, 0}, {1, 0, 1}}; // rotates the object void Block::rotate() { // square and evil shapes are the same in every direction if ((type != SQUARE) && (type != EVIL)) { int tmp[3][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) tmp[i][j] = grid[i][j]; } grid[0][0] = tmp[0][2]; grid[0][1] = tmp[1][2]; grid[0][2] = tmp[2][2]; grid[1][0] = tmp[0][1]; grid[1][2] = tmp[2][1]; grid[2][0] = tmp[0][0]; grid[2][1] = tmp[1][0]; grid[2][2] = tmp[2][0]; } } // moves the object a multiple of the block size in the x and y directions void Block::move(int dx, int dy) { int left = 0, right = 0; int newx = x+(SIZE*dx); if (grid[0][0] || grid[1][0] || grid[2][0]) left = 1; if (grid[0][2] || grid[1][2] || grid[2][2]) right = 1; // if the object is not at either side, let it move if ((newx >= (SIZE * left)) && (newx <= (SIZE * (9 - right)))) { x = newx; y += (SIZE * dy); } } // draw the object to the screen surface void Block::draw(SDL_Surface *screen) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (grid[i][j]) drawSurface(x+(SIZE*j), y+(SIZE*i), blockImg, screen); } } } // randomly selects a new shape and puts the block object back at the top void Block::newBlock() { type = rand() % 4; // make the evil block appear much less frequently if (type == EVIL) type = rand() % 4; switch (type) { case LINE: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) grid[i][j] = line[i][j]; } break; case L: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) grid[i][j] = l[i][j]; } break; case SQUARE: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) grid[i][j] = square[i][j]; } break; case EVIL: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) grid[i][j] = evil[i][j]; } break; } x = SIZE * 4; y = 0;} int Block::getGrid(int r, int c) { return grid[r][c]; } int Block::getX() { return x; } int Block::getY() { return y; }