/* The Exceedingly Tetris-Inspired Sport (TETr-IS) C++ Version Eric Marcarelli November 2008 */ #include #include #include "block.h" #include "grid.h" using namespace std; SDL_Surface *loadImg(string file); bool checkKey(int key); void drawSurface(int x, int y, SDL_Surface *src, SDL_Surface *dest); int main (int argc, char *argv[]) { bool quit = false; int startTime = SDL_GetTicks(); SDL_Surface *screen = NULL; // Set up SDL if (SDL_Init(SDL_INIT_VIDEO) != 0) { cerr << "SDL init failed. You lose!" << endl; return 1; } SDL_WM_SetCaption("TETr-IS", 0); screen = SDL_SetVideoMode(300, 550, 32, SDL_DOUBLEBUF); if (screen == NULL) { cerr << "SDL init failed. You lose!" << endl; return 1; } // these have to be below SDL init because their constructors load images Block block("block.bmp"); Grid grid("background.bmp", "block.bmp", 300, 550); SDL_Surface *gameover = loadImg("gameover.bmp"); block.newBlock(); // game loop while (!quit) { // keep track of how long it takes startTime = SDL_GetTicks(); // move block left or right if (checkKey(SDLK_RIGHT)) block.move(1, 0); if (checkKey(SDLK_LEFT)) block.move(-1, 0); // rotate block if (checkKey(SDLK_SPACE)) block.rotate(); if (checkKey(SDLK_ESCAPE)) quit = true; // make block fall block.move(0, 1); // if the block has reached a filled in area in the grid, it is added to // the grid and a new block starts to fall. if (grid.checkBlock(&block)) block.newBlock(); // delete filled in rows and move the blocks accordingly grid.process(); // draw everything to screen surface, then actually display screen grid.draw(screen); block.draw(screen); SDL_Flip(screen); // end the game if the 3rd row to the top is reached if (grid.gameOver()) { drawSurface(50, 250, gameover, screen); SDL_Flip(screen); while (!checkKey(SDLK_ESCAPE)); quit = true; } // keep it running at a fairly constant speed--100 is an arbitrary number while ((SDL_GetTicks() - startTime) < 100) SDL_Delay(5); } SDL_FreeSurface(gameover); SDL_Quit(); } // check if a key is pressed bool checkKey(int key) { // get updated kb states SDL_PumpEvents(); Uint8 *keystatus = SDL_GetKeyState(NULL); if (keystatus[key]) return true; else return false; } // load a bmp as an SDL surface SDL_Surface *loadImg(string file) { SDL_Surface* img = NULL; img = SDL_LoadBMP(file.c_str()); if (img != NULL) img = SDL_DisplayFormat(img); if (img == NULL) { cerr << "Couldn't load the image " << file << ". You lose!" << endl; exit(1); } return img; } // draw one surface onto another void drawSurface(int x, int y, SDL_Surface *src, SDL_Surface *dest) { SDL_Rect loc; loc.x = x; loc.y = y; SDL_BlitSurface(src, NULL, dest, &loc); }