// HW4 starter code -- Tetris // create and control the game Tetris #include #include #include "gp142display.h" #include "game.h" const int PIECE_MOVE_TIME = 4; // number of periodic events to wait before moving piece down // increase to make the game easier (i.e. slower) // pass key presses to the piece void handle_key(char keyPress, Game &game); // update the pieces, grid, and redraw the game void handle_periodic(Game &game, bool &gameOver); // true every PIECE_MOVE_TIME Periodic events // resets time to 0 when true bool time_up (int &time); int main() { bool quit = false; // = the Quit event occured bool gameOver=false; // = when a new piece can't be greated and game has ended int mouseX, mouseY; // location of mouse click -- not used in Tetris char keyPress; // which key was pressed to cause the Key event int current_time = 0; // how many periodic events have passed srand((int)time(NULL)); // initalize random number generator GP142Display display; // screen everything appears on including grid and pieces Grid grid(&display); // grid containing occupied squares Game game(&display, &grid); // controls the game including the piece and grid display.clear(White); display.setAnimation(Run); game.Draw(); // main event loop while (!gameOver && !quit) { switch (display.getNextEvent(mouseX, mouseY, keyPress)) { case Quit: quit = true; break; case Key: handle_key(keyPress, game); break; case Periodic: // slow the game down by waiting PIECE_MOVE_TIME periods if (time_up(current_time)) { handle_periodic(game, gameOver); } break; case Mouse: break; default: break; } } // Show that the game is ended display.write(-75,0,"GAME OVER",SeaGreen,24); // once game is over, wait until user quits while (!quit) { switch (display.getNextEvent(mouseX, mouseY, keyPress)) { case Quit: quit = true; break; default: break; } } return 0; } /****************** FUNCTIONS ************************/ // key presses manipulate the piece's movement. // 'j' moves left, 'l' moves right, 'k' rotates // the piece and ' ' (space) moves it down. // given the keyPress, the game will take the // appropriate action void handle_key(char keyPress, Game &game) { // **** implement handling of the keyPress here **** // redraw game to reflect the movement game.Draw(); } // control the game and set gameOver true if the game has ended. void handle_periodic(Game &game, bool &gameOver) { game.MovePiece(DOWN); game.UpdatePiece(); gameOver = game.IsGameOver(); game.Draw(); game.CheckRows(); } // true after every PIECE_MOVE_TIME periods, false otherwise // 0 <= time <= PIECE_MOVE_TIME bool time_up (int &time) { if (time == PIECE_MOVE_TIME) { time = 0; return true; } time++; return false; }