#include "grid.h" #include #include extern SDL_Surface *loadImg(std::string filename); extern void drawSurface(int x, int y, SDL_Surface *src, SDL_Surface *dest); const int Grid::SIZE = 25; Grid::Grid(std::string back, std::string block, int w, int l) { bgImg = loadImg(back); blockImg = loadImg(block); for (int i = 0; i<20; i++) { for (int j = 0; j < 10; j++) grid[i][j] = 0; } } Grid::~Grid() { SDL_FreeSurface(bgImg); SDL_FreeSurface(blockImg); } // removes filled in rows and moves remaining rows accordingly void Grid::process() { // start at bottom of grid int i = 19; while (i>=0) { // if there are no empty spaces in this row, remove it and move the rows // above down if (!checkRow(i)) { moveRows(i); } else i--; } } bool Grid::gameOver() { if (checkRow(3) < 10) return true; else return false; } bool Grid::checkBlock(Block *block) { int blockRow = ((block->getY()) / SIZE); int blockCol = ((block->getX()) / SIZE)-1; int bottom = 1; if (block->getGrid(2,0) || block->getGrid(2,1) || block->getGrid(2,2)) bottom = 0; // if the block has reached the bottom of the grid, it should be stopped // and added if (blockRow == (17+bottom)) { addBlock(block, blockRow, blockCol); return true; } // if the object is above all filled in rows we don't have to check it else if (checkRow(blockRow+3) < 10) { for (int i = 2; i>=0; i--) { for (int j = 2; j>=0; j--) { // there is a filled in block here if (block->getGrid(i,j)) { int thisRow = blockRow+i; int thisCol = blockCol+j; // check if the grid has a block under this one, and if so // add the block to the grid and return true if (grid[(blockRow+i)+1][blockCol+j]) { addBlock(block, blockRow, blockCol); return true; } } } } } return false; } void Grid::draw(SDL_Surface *screen) { drawSurface(0,0,bgImg,screen); for (int i = 0; i < 20; i++) { for (int j = 0; j < 10; j++) { if (grid[i][j]) drawSurface((SIZE*(j+1)), (SIZE*(i+1)), blockImg, screen); } } } // checkRow returns the number of empty blocks in each row (it counts empty so // !checkRow(#) will mean a full row) int Grid::checkRow(int row) { int ret = 0; for (int i = 0; i < 10; i++) { if (!grid[row][i]) ret++; } return ret; } void Grid::addBlock(Block *block, int row, int col) { for (int i = 0; i<3; i++) { for (int j = 0; j<3; j++) { // only replace filled in blocks (otherwise it may erase blocks) if (block->getGrid(i,j)) { grid[row+i][col+j] = 1; } } } } // move all of the rows above this row down one (removing the current row) void Grid::moveRows(int row) { for (int i = row; i>0; i--) { for (int j=0; j<10; j++) grid[i][j] = grid[i-1][j]; } for (int j=0; j<10; j++) grid[0][j] = 0; }