Tetris game: Semester project
DR. CATHERINE ANDERSON MCNEESE STATE UNIVERSITY
CSCI 282 OBJECT ORIENTED PROGRAMMING
CHAPTER 1
Tetris game, Part 1
Implementing the game board for the game Tetris with animation spawning a series of pieces.
TETRIS
1. Tetronimos
2. The game board
3. Scoring
SECTION 1
The game Tetris is a game based on a tetromino, which is a shape con- structed with four (tetra) squares. There are seven unique ar- rangements of four bricks. By unique we mean that even with limitless rotation you cannot bring one unique shape to resem- ble another unique shape.
The seven arrangements are shown below. An arrangement is valid only if each brick aligns
with at least one another brick along its full side.
In the game of Tetris, each of these shapes or tetrominos has a different color. Historically there is no “standard” color scheme. In fact, the very first game had all bricks the same color. My color scheme is shown below. The names you must use for each of the different Tetris bricks are shown below. :
A.El B.Long C. Jay D.Ess E. Stack F. Zee G. Square
2
The game board is a grid, some times referred to as the well. During the game, tetris bricks appear in random order at the top of the well and fall towards the bottom of the well. During their fall, the player is allowed to rotate the shape by 90 de- grees each click. The player can also move the shape right or left. After each shape is as low as it can fall, it will freeze into place and a new shape will appear and being falling. The ob- ject of the game is to arrange the pieces at the bottom of the well such that no empty spaces occur.
When a row across the well has been filled with brick segment, the filled row will disappear with all col- ored segments above it dropping to occupy the vacated row. The player scores 100 points for each single row that is cleared like this. If two rows are fill at once, 300 point are scored. Three rows at once scores 500 points and four rows scored at once is worth 1000 points.
The game continues until a new brick has no free space in which to be placed.
Alternate features (extra credit) 1. There can be a button that allows the player to increase the
speed of the the falling shapes. For each increment of
speed increase, the score for each combination of rows be- ing cleared goes up.
2. There can be a button that allows the player to “hard drop” a shape, which means it is positioned immediately at its low- est possible level. This allows more shapes to be places in an interval of time.
3
GAME FEATURES FOR PART 1
1. Game board with animated dropping shape
2. Shape must stop dropping at the bottom of the well.
3. New shape must appear and start dropping after current shape is at the bottom of the well
4. Order of pieces appearing must be random.
SECTION 2
Evaluation Criteria for Tetris Game Part 1.
For the implementation of this game you must adhere to sev- eral requirements that are imposed to give you practice in Ob- ject Oriented Design. You are expected to follow the UML dia- gram shown below. This will get you started on a good OOD (object oriented design). All classes must be present and used as indicated.
I have given you method in each class that must be present, but you are free to create helper methods. I recommend that you adhere to the principle of “distinct purpose” when creat- ing methods. Each method should have a single purpose. If you cannot easily name the method, chances are that you are trying to do too much within the method.
4
Here is a description of the classes along with their appropri- ate methods.
1. TetrisWindow – Is a container for the game display and is a subclass of JFrame. This is the executable class and as such needs a main method. This class is responsible for the action listeners needed to run the menus that you will be adding in Part 3 of this assignment. The primary functional- ity of this class in part 1 is to instantiate both the Tetris- Game and the TetrisDisplay objects, and to provide a con- tainer for the GameDisplay to be housed in and seen. For this part, only the Constructor and the main method are re- quired.
2. TetrisDisplay – This class creates the graphic game dis- play by extending a JPanel. It is responsible for the event listeners for key clicks and for telling the game which moves were made by translating the key clicks. This class is also responsible for the animation. The only ‘data structure’ (term used loosely) needed in this class is a TetrisGame ob- ject. The class has a constructor that take a TetrisGame ob- ject as a parameter. The methods are: • processMove ()- called within the actionPerformed
methods of the anonymous ActionListener defined for the Timer. It will call the games makeMove method and pass it the integer constant for DOWN (defined in the game class).
• paintComponent(Graphics g) – will create the dis- play of the Tetris game. The Well and all bricks within the
well should be drawn separately from the actively “falling brick”.
3. TetrisGame – This game contains all the logic for direct- ing the game; to • respond to the moves reported by the Tetris Display
class, • update the game board and status after each move. • removes full rows and adjusts score • game end detection.
The methods of the TetrisGame class are as follows:
• initBoard( ) – Should reset each cell back to its “empty” condition, possibly -1.
• spawnBrick( ) – Should randomly generate a new “falling brick”.
• makeMove( int moveCode) – the move code should indi- cate which direction the falling brick should move; down, left, right, up, or rotate. For part 1, the only move is “down”
• validateMove( ) – checks the tentative move to make sure the brick is in bounds. For part one, it simply has to check that the brick is not below the bottom of the well.
4. TetrisBrick (abstract class) – This is the superclass that contains all of the attributes and methods that all seven brick types bricks have in common. These will be inherited by its seven subclasses. There are several abstract methods that TetrisBrick must have that each subclass must over-
5
write. For part 1 of this project, the needed abstract method is initPositions. This must be overwritten is each subclass to allows each brick to start at the appropriate place for its shape.
Each of the subclasses listed below must overwrite the ab- stract methods initPositions from the TetrisBrick class: El- Brick, JayBrick, EssBrick, ZeeBrick, SquareBrick, Line Brick and StackBrick.
Progression of Assignments that will result in a com- plete Tetris game.
The full Tetris game project will be due in three parts . The general functionality that will be due in each part is discussed in detail in each chapter of this manual. This is outlined be- low.
Part 1: Create all of the classes in the UML and have them working together. The brick must be randomly generated and fall to the bottom of the well at which point it will disappear and a new brick appear at the time of the well.
Part 2: Add key listeners that allow the user to move move the falling brick left and right as well as rotate it. boundary checking as well as color checking must be implemented. When the brick has fallen as far as it can without covering any other colored segment in the well, its shape must be trans- ferred to the well. A “new game” option must be available from hit the key ‘n’.
Part 3: In this part, A full line must “dissappear” and the players score increase by 100 points. Menus must be in place to allow a user to save a current game to file and save a game along with tracking a leader board. The “new game “ options must also be avialable from the menu .
Extra credit: Scoring multiple lines, multiple “hardness” lev- els to start game (faster drop rates), hard drop button. Any other extra feature will be considered for extra credit. Remem- ber, this is probably the first project you have been given in a Computer Science class. It can be used to show prospective employers what you are capable of, so it is recommended that you pay close attention to good programming form and com- pleting all of the extras will make your project stand out.
Evaluation Criteria:
You are expected to follow good programming form. You will loose substantial points for not doing so.
Pay close attention to the “No numeric literals” conven- tion. This states that no numeric literals are allowed in code except to assign a value to a variable. the only exception to this are the values of 0,1 or 2. This is especially important when forming your graphics.
You should assign needed values to variables from the start. There is never enough time at the end of a project to correct sloppy practices at the start of the project. You will loose sub- stantial points for not following this convention. Here are sev- eral other requirements.
6
1. You must have all of the classes with the methods shown in the UML. However, you may have additional helper meth- ods (in fact it is recommended) in each class but the stated functionality of each class must be kept separate from other classes. If in doubt ask.
2. Game and Display objects instantiated in Window class.
3. Display class controls animation and reports moves to be made to the game class.
4. Game class controls states of the game. It receives the move to make from the display class, validates it and determines when the brick and reached its stopping location.
Use the Criteria table on to the right as a check off list BE- FORE submission. You should know what your score will be before you submit your work. Remember, if one part of the criteria is not correct, all points for that criteria are lost. There is no partial credit. This is to establish the importance of completing a task and attention to detail. If you have any questions on a criteria, ASK!
Enjoy learning and don’t wait to long to come for assistance!!
7
CHAPTER 2
Tetris game, Part 2
Functionality to be added • Transfer of color • Color Validation • Move right and left • Side boundary validation • Rotate
PART 2 CRITERIA
1. Shape incorporated into board when it stops falling.
2. Pause key on typing space bar
3. Key listener installed in TetrisDisplay class
4. Functionality of left and right move of shape
5. Validity checking on left and right move.
6. Functionality of rotation
7. Validity checking on rotation move.
8. New Game when ‘N’ is pressed
SECTION 1
Evaluation Criteria In part 2, you will be evaluated on new aspects of the game. The points you earned points in Parts 1 will not earn points this time. However, any errors not corrected from previous parts will earn you penalty points. The UML is shown below, with all new methods shown in red.
9
For this phase of the development of the Tetris game we will be accomplishing the following:
•Transfer the brick color to background •Move Tetris brick right and left •Rotate Tetris brick •Validation of move •New game capability
1. TetrisWindow – no new methods. 2. TetrisDisplay – additional methods for
• translateKey () – called within the keyTyped method of the anonymous KeyListener. This method will call the make move method from the game with the appropriate move code.
3. TetrisGame – New methods: • transferColor – when a brick has no place to fall, it’s
color is transferred to the board array in game. • newGame – will start a new game
4. TetrisBrick (abstract class) – New methods: • rotate- abstract class in Tetris brick, and must be over-
written in each individual brick subclass. • unrotate- used if validation of rotation move fails. It is
an abstract class in Tetris brick, and must be overwritten in each individual brick subclass to undo the rotate move
• moveLeft- translates each segment of the brick one cell to the left.
• moveRight – translates each segment of the brick one cell to the right.
• moveUp – used if validate down move fails. Translates each segment of the brick one cell to the right.
Functionality to complete in Part2:
It is recommended that you proceed to build up you game one functionality at a time, debugging as you go. Here is the recom- mended order.
1. The colors from the current falling brick must be incorpo- rated into the background when the brick has stopped fal- ling and no brick may fall over a colored brick in the back ground (color validation).
2. You must install the key listeners in the Display class.
3. Pause key enabled that toggles pausing the animation of the game and restarting it.
4. The functionality of the left and right arrow keys must com- plete with move validation, meaning it cannot over run the side boundaries of the game board or move over a colored segment.
5. The rotation method for the game class must be complete (calling the rotation method of the falling brick) along with validation , meaning it cannot over run the side boundaries of the game board or move over a colored segment.
6. New Game when ‘N’ is typed
10
Use the Criteria table below as a check off list BEFORE sub- mission. You should know what your score will be before you submit your work. Remember, if one part of the criteria is not correct, all points for that criteria are lost. There is no partial credit. This is to establish the importance of completing a task and attention to detail.
Also, use the penalty table to the right to check for possible loss of points for poor programming form or improper submis- sion practice. Again, full points deducted!
If you have any questions on a criteria, ASK!
Enjoy learning and don’t wait to long to come for assistance!!
11
INCORPORATING COLOR AND VALIDATION COLOR
Color of the current brick entered into its last valid position on the board.
A move cannot allow the current brick to cover any existing colors segments.
SECTION 2
Incorporation of color into The first functionality to be added is incorporating the color of the current brick into the back ground. This is fairly straigth forward. Remember the following
The well is divided into cells that are initial to zero or -1 or any number you wish to use to indicate no color. You should coor- dinate the color number of a specific tetris brick with the in- dex of the rray of colors in the display class.
The diagrams that follow were created by drawing an outline around each cell represented by the board in the game class.
Then I printed the value of each cell to the center of that cell. This is for teaching purposes. You can see that as the brick falls (fig. A) the color is not incorporated into the the board.
12
The falling brick is drawn over the board. But when the brick reaches the point where it cannot fall without violating either a boundary or a color condition ( fig. B ), then the color of that brick is incorporated into the board and a new brick spawned. see each cell. In this example the color number is 5.
Each time the falling brick stops, the color is incorporated into the back ground ( fig. C through fig. E ). This process contin- ues until there is no room at the top of the board, at which point the game is over.
The process of incorporating the color into the board in simple. I consists of assigning the color number of the falling brick to the coordinates of the board that match the coordinates of each segment of the falling brick.
The pseudo code for this process is given below
1. REPEAT for each segment of the brick 2. board coordinate stored in segment <– brick color number
Color validation is the process of going through each segment of the falling brick, taking its coordinates (row and col of board) and checking that position of the board to make sure that the value stored there is not a color number. In the case of this ex- ample, check that the number is not zero. If the value is not zero, the move in NOT VALID.
13
WHAT AT THE STATES OF THE GAME
1. Moving left – subtract 1 to each column
A. Check that column is not less then 0
B. Check that there is no color in new positions
2. Moving right – add 1 to each column
A. Check that column is not less then maximum Column
B. Check that there is no color in new positions
SECTION 3
Moving left and right The process of moving a brick to the left or right, is the same for all bricks and as such this method must be implemented in the TetrisBrick class.
To move left, the column coordinate of each segment of the brick is decremented.
To move right, the column coordinate of each segment is incre- mented.
To validate the left move, it must be in bounds (each segment must have a column number greater than -1) and it must be color validated (see section 2 for this technique). If the move is invalid, it must be reversed (move right).
Like wise, to validate the right move, it must be in bounds (each segment must have a column number less than the num- ber of column in the array) and it must be color validated (see section 2 for this technique). If the move is invalid, it must be reversed (move left).
14
VALIDITY OF ROTATION MOVE
1. rotation – each sub brick has a unique rotation method
A. Check that columns is not less then 0 or greater then maximum column
B. Check that rows are not greater than maximum row
C. Check that there is no color in new positions
SECTION 4
Rotation Since the coordinates for each type of brick are different, the method to rotate the brick is different for each brick and as such must be implement in in each individual subclass of the TetrisBrick. What you should notice is that there is symmetry amount the different brick.
For example, the square brick has only one appearance, no matter how you rotate it. As such the rotation method can be and empty method.
The long brick has only two appearances; horizontal and verti- cal and as such only needs two orientations always pivoting on segment 2 as as such segment 2 does not change. The same can be applied to the EssBrick and JayBrick. Or
The 15
StackBrick, ElBrick and JayBrick have all four orientations that must be rotated through.
For example, the StackBrick will rotate around segment 2.
The segment that is the pivot point does not change.
The unrotate method is needed when the rotate method pro- duced an invalid move. This invalid move must be undone.
For a brick with only two orientations, the unrotate can be ac- complished by simply rotating one more time. Forw four rota- tions, simply rotate three more time. Remember, you can call a method from the body of another method. Reuse your code, don’t reinvent!
16
CHAPTER 3
Tetris game, Part 3
Completing the logic of the Tetris game for removing full rows and scoring
Game-over detection and indication
Establishing a leader board
FULL GAME FUNCTIONALITY
1. filled rows scored and disappeared
2. All bricks above scored line drop down to fill blank line
3. High score must be tracked, displayed in sorted order and saved to file.
4. Menu system in place with two pull down menus
SECTION 1
Evaluation Criteria for Tetris Game Part 3.
In part 3, you will be evaluated on new aspects of the game. The points you earned points for on Parts 1 and 2 will not earn points this time. However, any error s not corrected from pre- vious parts will earn you penalty points.
In Part 3 you will be finishing up your game such that full lines will be detected, removed and scored. Also a High score leader board must be established.
Itemized Part 3 requirements:
1. Full line detection must be complete followed by full line disappearing and score increasing.
2. All rows above disappear line should drop one row.
3. Score must be incremented by 100 if just one line disap- pears, 300 for two lines, 600 for three lines and 1200 for four lines.
4. Score must be shown on the Game display.
5. High score leader board must be saved even after the game is closed and reopened. Scores must be sorted.
6. There must be a menu bar with two pull down menus. One Menu items must have an option to display leader board, and one to delete all high scores to start over. The other Menu should deal with the new game, or other extra credit items such as save game to file, retrieve game from file.
18
Please read all criteria over carefully. Remember, once you have started an evaluation, you may not change anything with- out penalty. Use the table to the left check your work.
19
QUESTIONS TO CONSIDER
1. How many rows have to be checked?
2. What happens if more than one is detected?
3. What happens if the rows are not consecutive?
SECTION 2
Detecting full rows Detecting Full rows. I will leave how to score a full row to you. So there are no required methods. I recommend that you use helper functions that looks for full rows. But you have to realize you can have one, two, three or four full rows with one brick placement. The game boards below show various situation for row scoring. The full lines should be detected and cored BEFORE the next brick is spawned.
The images above depict one full row scored.
The images above depict two full rows scored.
20
The images above depict three full rows scored.
The images above depict four full rows scored.
But you must realize that the rows do not need to consecutive. Full rows can have a row with spaces in between them.
Please note that the only rows that need to be checked are those that involve the latest brick to be positioned in the board. Possibly a helper function in the Tetris brick call
getMinimumRow and getMaximumRow would be use- ful.
I recommend that you use helper methods to accomplish sub tasks. This improves readability of your code and is you don’t you could have up to 4 to 5 nested loop structures, which can be difficult to debug.
Some suggested methods
• rowHasSpace( int rowNumber) – returns true is space in row
• rowHasColor( int rowNumber) – return true is color in row
• copyRow(int rowNumber) – copy row number to row be- low.
• copyAllRows(int rowNumber) – calls the method copy- Row o each row starting with rowNumber and above (lo- cated higher in the well, or at a lower row numb).
A suggest approach would be as follows:
1 .Determine the range of rows to be checked. 2. currentRow – highest row number in range 2. REPEAT for each row within the range starting with max 3. IF rowHasSpace( int rowNumber) is false 4. call copyAllRows(currentRow) 5. current row is incremented (so that when for loop decrements current, it remains the same 6. min row of range is decremented 7. END IF 8. END REPEAT
21
hint: once you have copied the row above the deleted row to the row that was deleted, you have to recheck that for fullness, unless the row was not in the range of rows affected.
Now this suggested approach is how to get the rows to disap- pear. You also have to work out how to score this process. I would recommend that you count the number of row removed and then figure out the score after going through all rows that need checking.
Once again, I will let you determine how you do this removal of rows. I want you to practice good function design by mak- ing functions short and concise. I have given you a couple of suggestions.
Go forth and conquer!
22