Developing games in any programming language is a difficult undertaking. All but the most simplistic games require programmers to track many more factors than traditional textbook programming exercises require of students. However, if you are a Java programmer who wants to move into the world of video game development, then a simple version of "Tetris" is a good place to start: The exercise will introduce you to multiple object interactions and tracking movement across a game screen.
- Skill level:
Other People Are Reading
Create the JPanel you will use as the canvas for your "Tetris" game with the syntax "JPanel MyTetrisCanvas = new JPanel();" where "MyTetrisCanvas" is the name you will use for this object throughout your program.
Create the classes for the objects that will represent the "Tetris" pieces. Each shape you wish to use should have its own class. These classes need to include at the very least an array of the dimensions that match your piece size, with areas which are part of the piece identified by element values of "1" and open areas identified by element values of "0."
Add a boolean value to your "Tetris" object classes to indicate whether a piece is still able to move or has come to rest.
Create a function, such as Java's built-in "Random()" function, to randomly select among your classes for each new piece that will spawn at the top of your board.
Create an array in your main thread to represent the "Tetris" area, making its dimensions correspond to your desired game field. Initiate the array, with every element having a value of "zero." If the square is occupied by a piece, then it's value will be "1" and if open it will stay "0." You can change these values with the syntax "MyFieldArray[x][y] = n" where "x" and "y" are the appropriate Cartesian coordinates that approximate your element, and "n" is either "1" or "0."
Create a method that adds "1" to each element on your "Tetris" area array for areas occupied by a new piece you spawned. Do this by iterating through the "Tetris" object array that represents the object's shape and adding one to the corresponding area on your "Tetris" area array.
Create a method to move a "Tetris" object down the field by setting the array values into which the piece is moving to "1" and resetting any areas no longer occupied by the piece to "0."
Create a method that checks the area each piece is about to move into as it moves down the board. If any part is about to hit an existing piece, set that object's boolean value to false and spawn a new "Tetris" object at the top of the field.
Create a method that checks whether the active "Tetris" piece can no longer move down from the top part of the screen -- specifically, if a newly spawned piece comes to rest once it spawns. This will trigger the end of the game.
- 20 of the funniest online reviews ever
- 14 Biggest lies people tell in online dating sites
- Hilarious things Google thinks you're trying to search for