tetris game using java

profilerajeev4
CSCI_282_TetrisGame_Lab_4_manual.pdf

CHAPTER 1

Lab4: Tetris game, Getting Started

Setting up the classes with attributes and method headers. Drawing the well ( the background).

TETRIS

1. The Tetronimo (Tetris brick)

2. The game board

3. Scoring

SECTION 1

The game You will be implementing the game of Tetris as a semester project. This will require that you use both aggregation and inheritance in a good OOP design that is provided for you by way of UML

Tetris is a game based on a tetronimo (A.K.A.: Tetris brick), a shape constructed with four (tetra) squares. To be a valid TetrisBrick, each component segment of the brick must be touching at least one full side of another segment.

There are seven unique Tetris bricks. By unique we mean that even with limitless rotations you cannot bring one unique shape to resemble another unique shape.

In the modern implementations of the game of Tetris, each type of Tetris brick has a different color but consistent color (meaning all bricks of the same shape always have the same color). However, there is no “standard” color scheme. My color scheme is shown below. You may chose your own. BUT the color must remain constant during a single game. There is no random selection of color per type of brick gener- ated. For example, using the color scheme shown here, all

2

square bricks(G.) must be red and all long bricks (E.) must be red.

The names you MUST use for each of the different Tetris bricks are shown below with official class name in parenthe- sis:

A.El brick (ElBrick) B.Jay brick (JayBrick) C.Ess brick (EssBrick) D.Zee brick (ZeeBrick) E.Long brick (LongBrick) F. Stack (StackBrick) G. Square brick (Square-

Brick)

In the abstract, the game board is a grid. However, it is shown in the graphics display as “the well”, a black outline that the bricks fall through. 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 Tetris brick by 90 degrees each click. The player can also move the brick right or left. After each brick is at its

lowest point, it will freeze into place and a new Tetris brick will appear and being falling. The object of the game is to

arrange the bricks at the bottom of the well such that no emp- ty spaces occur. When any row across the well has been filled with brick seg- ments, the filled rows will disappear with all colored segments above it dropping to occupy the vacated row. The player scores 100 points for each single row that is filled and cleared like this. If two rows are fill at once, 300 point are scored. Three rows at once scores 600 points and four rows scored at once is worth 1200 points.

The game continues until a new brick has no free space in which to appear at the top of the well. At this point a declara- tion of “Game over” is made.

Classic controls to be implemented are as follows: • Left arrow key - Moves the falling Brick left one segment. • Right arrow key - Moves the falling Brick right one segment. • Down arrow key - Moves the falling Brick down one seg-

ment. yes this is the same direction the brick is falling in, but you can “hurry it along”. with the down key.

• Up arrow key - Rotates the Tetris brick around one segment of the brick.

These are the controls you will be required to use. The reason I insist on you using these controls is because I have to evalu- ate your games, meaning, I have to actually play your games. And it is more efficient for that purpose if all controls on all games are the same.

3

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 must increase.

2. There can be a button that allows the player to “hard drop” a shape, which means it is positioned immediately at its lowest possible level. This allows more shapes to be places in an interval of time.

The evaluation rubric is found at the submission site of Moo- dle. Please note, this rubric is how points are earned and how points are lost. It is not exhaustive. If an implementation violates the intent of the game, even though the aspect is not explicitly listed, you can still loose points. I have given you examples of the appearance of the game and how it should run. You should adhere to this behavior. If you have any questions on your implementation, it is your responsibility to ask and clarify your understanding. Otherwise, you risk loos- ing points.

4

FOUR SEPARATE SUBMISSIONS

1. Lab

2. Part 1

3. Part 2

4. Part 3

SECTION 2

Progression of Develop- ment for this project

You must work alone on this project. No teams are allowed.

Progression of Assignments that will result in a com- plete Tetris game.

The Tetris game project will be done in four parts . The gen- eral functionality that will be due for each part is discussed in detail in each chapter of this manual. This progression of im- plementation is outlined below.

Introduction Lab (lab 4):

• Create all of the classes in the UML with empty methods where not needed to create the display of the well (see next section). For this part, all un-implemented methods will have no parameter lists and return void. This will be adjust- ed as methods are implemented.

• Draw the outline of the well.

Part 1:

• The brick must be randomly generated and fall to the bot- tom of the well

• When a brick reaches the bottom, it will disappear and a new brick appear at the top of the well.

• All methods listed in the Part 1 UML class diagrams must be implemented.

5

Part 2:

• Add key listeners that allow the user to move move the fall- ing brick left and right as well as rotate it.

• Boundary checking as well as color checking must be im- plemented. When the brick has fallen as far as it can without covering any other colored segment in the well, its shape must be transferred to the well. Two additional keys must also be complete:

• A “new game” option must be available from hit the key ‘n’. Game

• The animation must pause with the space bar is hit Part 3:

• Full rows must “disappear” and the players score increase appropriately.

• Bricks from the rows above the disappeared row, must fall down to fill in the vacated space.

• Menu item must be in place to allow a user to save a current game to file with a file new that can be entered. No default file names are acceptable

• Menu item must be in place to allow a user to retrieve a saved game from a file name that can be entered. No de- fault file names are acceptable

• Each time a game is won, the score must be automatically added to the leader board (if it qualifies). This must ask for the players.

• The “new game “ options must also be available from the menu . You must also be able to Save a game to a file and retrieve this game.

Extra credit:

Remember, 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 rec- ommended that you pay close attention to good programming form and completing all of the extras will make your project stand out.

• Multiple “hardness” levels to start game (faster drop rates),

• Sonic drop button.

• Sound effects for each action (not background music, which does not count of extra credit).

• Special visual effects: dust cloud when row disappears, con- fetti when a multiple row disappears.

• etc...

But a reminder. If you want credit of the extra credit work, all of the base requirements must be correct and the submission must be on time.

NO extra credit will be given if there are problems with the base problem or if the submis- sion is late, no matter how “nice” the extra credit ef- fects are.

In other words, you can not make up for your work being late or your game not working to spec. by adding extras.

6

The purpose of the extra credit is to give those that correctly implement the base program on schedule, to have an addi- tional challenge to further their experience in java.

Your base strategy is to start as soon as the assignment is cov- ered in lecture and to ask questions when you run into a road block. If you wait until the last minute, you will not get this project done.

Also, each student must work on their own. You are allowed to discuss the game and algorithms between students, but each student must write there own code. Copying code when expressly told not to, is an “F” on the assignment.

7

CONTENT

1. Definition of Abstract class

2. Implementation of an abstract class

SECTION 3

Abstract class What is an abstract class:

An abstract class in one that is not meant to be instantiated by calling it’s constructor in a design. Rather, it serves as the su- per class for a series of sub classes that will be implemented. The abstract class can also have abstract methods that must be defined uniquely for each subclass that inherits the ab- stract superclass. .

An example that you will be working with in this project is the TetrisBrick. This class is the super class for all 7 tetris shapes, which will each be a class.

The UML relation of these classes is shown below.

8

These subclasses are unusual in that they overwrite the ab- stract methods of the super class as opposed to providing any additional attributes that the other sub classes don’t have.

Now remember, a subclass and its super class share the rela- tion subclass is a superclass. Because of this, a variable can be declared as superclass, but can be assigned an instance of the subclass. An example of this in the Tetris project would be your Falling Brick attribute in the TetrisGame class (see UML for part 1).

TetrisBrick fallingBrick = new StackBrick(...);

The Tetris brick was made abstract because each of the sub- classes needed to have a method to initialize them, which needs to be unique to the specific sub-brick. So, the super class has this method, initPosition() , as abstract in the class definition of the super class, so that they both must be over- written in the subclass. The next section goes over these de- tails.

Implementation of an Abstract class.

To designate a class as abstract, the key word abstract must appear in the class header. For example, for the tetris brick, the class header would be:

public abstract class TetrisBrick { }

The use of the key word “abstract”disallows the constructor from being called to instantiate an object. In other words, if you try to, you will get a compiler error.

An abstract method, of which there will be several in this project, also contain the key word abstract. The initPosition is declared as follows:

public abstract void initPosition(int center_x, int center_y);

Please note that the parameter past in the initPosition method is the location of the center of the brick. Other differences for an abstract method is the terminating semicolon and the ab- sence of a method body.

This means that the subclass that inherits this class must pro- vide a method with the exact same name, minus the key word abstract and semicolon, and having method body with code to provide the functionality of the method.

9

REQUIREMENTS FOR LAB 4

• Select partner for Semester Project.

• All classes must be implemented with empty method bodies unless needed for lab.

• TetrisWindow Class must have the 4 minimal method set up methods calls, as well and creating the display and game objects.

• TetrisGame must initialize the rows and columns related attributes to be used by the Tetris Display class.

• TetrisDisplay Class paintComponent class must be implemented to draw “Well” properly sized for game size (number of rows and columns of game

• In-source code documentation must be complete is EVERY FILE

SECTION 4

Getting Started In this “Lab” you will be setting up the eleven classes you will be using for the Tetris game implementation which is your semester project.

Below you will see a UML for the Tetris game that will be used for Lab 4 and PART 1 of the Tetris project.

10

This UML will be updated for each part of the Tetris Project. This UML is provided as a guide for a good object oriented design of this game, where every class and resulting object has clear cut responsibilities. For the implementation of this game you must adhere to the design laid out in this UML. Any more or any fewer classes will result in ZERO points scored on that part of the project.

I have given you methods for each class that must be present, in the indicated class shown in the UML. If the methods are not in the proper classes (meaning, you do not adhere to the separation of responsibilities as outlined) you will losses ma- jor points.

However, while all methods in UML must be present, you are free to create helper methods, additional methods called by the required methods to perform subtasks. I recommend that you adhere to the principle of “distinct purpose” when creat- ing methods. Each method should have a single clear pur- pose. If you cannot easily name the method, chances are you are trying to do too much within the method.

A list of classes for this implementation(use as a check off as you create them) is as follows

• TetrisWindow - executable • TetrisDisplay • TetrisGame • TetrisBrick - Abstract super class for all other Brick

classes • SquareBrick

• StackBrick • LongBrick • ElBrick • JayBrick • EssBrick • ZeeBrick

The next section of this document talks about the division of responsibilities as it applies to this lab. This discussion will continue in Part 1, Part 2, and Part 3, covering the appropriate methods to be implemented in each part.

TetrisWindow This class is the window that holds the game display and is a subclass of JFrame. This is the executable class and as such needs a main method. For Part One, the primary functionali- ty of this class is to set up the window and to instantiate both the TetrisGame and the TetrisDisplay objects. In other words to provide a container for the GameDisplay to be housed in and seen. For this part, only the Constructor for this class and the main method are required.

In the constructor, the four minimum methods that set the title of the window, set the size of the window, set the default action on close and set the window to visible. Remember this last action should be the last line in the constructor with the game and display instantiated and the display added to the window before the window is made visible.

11

In the main method, you simply have to create an instance of the Tetris window.

TetrisDisplay This class creates the graphic display that shows the status of the game by extending a JPanel. The class has a constructor that take a TetrisGame object as a parameter. This class is not responsible for the logic of the game. In later parts of this im- plementation, it will communicate which move the player wants to make (through the keys pressed), but it is not re- sponsible for determining if the move is valid or what the re- sult of the move is. It simple communicates the desired move, in terms of left, right, down or rotate (implemented in PART 2), and displays the status of the game.

In this lab, the only method that must be implemented is the the paintComponents method.

paintComponent() - The method that will create all custom graphics for the JPanel subclass. For the full implementa- tion, this will be re- sponsible for creating the Well outline, the falling brick, the background with the

colors of past fallen bricks, the score board, and finally at the end of the game, the Game Over indication.

For this lab, the only image that must be drawn is the outline of the well as shown below and to the right. It is recommend- ed that each drawing task has its own method and as such the task for drawing the well could be: public void drawWell (Graphics g) which is then called from the paintComponent method. This is required.

Now, there are several ways you can go about drawing the well. You can use three indi- vidual rectangles to draw the U shaped outline (as shown to the right) using cellSize as the width of the outline. The height and width of each of the individual rectangle are calcu- lated by using the number of rows or column as well as the cellSize. The small dots shown in the upper left corner of each rectangle represent the x and y coordinates of the starting points of the rectangle.

Another method of drawing this outline of the well would be to use a polygon with eight points. This would require that you calculate each point based on the number of rows and

12

columns of the well. The order of the points should be the or- der that the polygon is drawn, shown below. Of course you can start at any of the points, as long as the wrapped order is followed. In the image below, p1 is the first point, followed by p2, then p3, etc.

Remember, this rendering of the well should change to reflect a different number of rows and columns in the game as well as different cellSize in the display class. This will be tested dur- ing evaluation in lab.

For instance, if we passed the values of 10 rows 20 columns to the game construction fro the TetrisWindow, then the image would be as shown below.

TetrisGame: This game contains all the logic for directing the game, such as ...

• responding to the moves communicated by the Tetris Display class,

• updating the game board and status after each move. • removing full rows and adjusting score • end-game detection.

The constructor will take as argument, the number of rows and columns that will be in the well and initialize these attrib- utes.

13

For this lab, the only methods the will need to be fully im- plemented is the constructor and the getRows and getCols methods. All other methods from the UML must be added as empty bodies except where a return value is needed to com- pile.

TetrisBrick This class is an abstract class, meaning it is never instantiated, only inherited. TetrisBrick is the superclass that contains all of the attributes and methods that all seven brick types bricks have in common that don’t require unique actions based on the particular TetrisBrick subclass. Please see the UML for which methods can be implemented in the TetrisBrick Class and which must be abstract in the TetrisBrick Class to be overwritten in each of the subclasses.

This class should be created before the subclasses, simply be- cause it needs to be in existence to be inherited by the sub- classes. And remember, an abstract methods does not have a method body in the Tetris class, but must have a body in the subclasses.

14

GAME FEATURES FOR PART 1

• All requirements for lab as indicated in previous section.

• No numeric literal unless assigned to a variable

• No package information in any files

• Only source code files properly zipped using compression software that generates .zip file.

• Zipped file should unzip to a directory showing only source code files. No additional directories such as the project directory of the IDE or a src directory.

SECTION 5

Evaluation Criteria 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 several other requirements.

1. You must have all of the classes with the methods shown in the UML. Game and Display objects instantiated in Win- dow class.

2. Display class controls animation and reports moves to be made to the game class.

3. 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

15

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!!

16

  • Lab4:
  • Tetris game,
  • Getting Started
    • The game
    • Progression of Development for this project
    • Abstract class
    • Getting Started
    • Evaluation Criteria