Im just new to Java and I found this good tutorial for creating a Java Tetris Game.
I dont have a mentor or a tutor to help me with this - Ive been looking for one for ages :( so currently im self learning Java and PHP :)
Anyways heres the website I found: http://zetcode.com/tutorials/javagamestutorial/tetris/
One method of the program I dont get in the Shape.java
class:
public Shape rotateLeft()
{
if (pieceShape == Tetrominoes.SquareShape)
return this;
Shape result = new Shape();
result.pieceShape = pieceShape;
for (int i = 0; i < 4; ++i) {
result.setX(i, y(i));
result.setY(i, -x(i));
}
return result;
}
Why do we need to create a new Object Shape result = new Shape();
if can already get the current piece from the pieceShape
variable?
It seems the naming is a bit misleading in this tutorial. The class called Shape
represents a single item that falls down. The Tetrominoes
enum
seems to be describing which kind of item it is (i.e. it's "shape"!).
So the code you posted creates a new item and specifies its shape.
The rotateRight()
and rotateLeft()
methods don't modify the shape itself to allow the tryMove()
method to check if the move is legal and ignore it if it isn't (for example if you'd rotate an item into the wall). tryMove()
simply keeps the old values (including the old Shape
instance) when the move is not allowed. If rotateLeft()
/rotateRight()
modified the Shape
then it would have to undo that operation, which would complicate the code.
Also, there are a few nitpicks with this code:
I'd call the Tetrominoes
class Tetromino
, as enum
types are usually named in the singular (since you often reference a single element: Tetromino.SquareShape
.
I'd add the information about the concrete coordinate of each Tetromino
into that enum
, effectively putting much of the logic from the setShape()
method into it.
The Board
class mixes the logic and the presentation, it should be separated (makes it much easier to test).
For example the Board
class could implement all the logic without any of the graphics (i.e. don't reference anything from java.awt
or javax.swing
). Then you'd write a BoardPanel
that draws the state of the Board
and interacts with the user, calling the appropriate Board
methods.
The method you've posted returns a shape that is rotated left. If you didn't create a new Shape, the original shape, which is a field of the class and used everywhere else, would have been rotated.
In the case of the square shape, which isn't changed when rotated left, you can still return the original one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With