Question

I'm making a tetris game in Java, and I am having a little trouble making the current piece stop when they hit another piece that's already landed. I have separate classes for each tetromino shape. When the currentPiece is falling, the shape with the lowest Y coordinate and the same X value as current is set as the stop point for currentPiece. The problem is that the piece goes through blocks adjacent to currentPiece's center and it is tedious to code for all possible shapes and rotations

Is there a better way of doing this? Basically, my question is, How to handle bounds of tetris pieces?

Link to my java files: http://goo.gl/Ms8Mj (forgive the messiness)

Each block is represented by a table of values, for the L shape it is:

{0,0},{1,0},{0,1},{0,2}

The "middle" block is treated as the origin. I am considering making a 2D boolean array to if a location is occupied or not.

Was it helpful?

Solution

Perhaps build a 2d view representing pieces already places. eg. (o's represent empty spots, x's represent placed pieces)

|ooooo|
|oooox|
|ooxxx|
|xxxxx|

Look at your piece and its current position. Simulate moving it to the spot it needs to go, then check if any of the x/y co-ordinates overlap. If so, then it can't move there.

eg. if you've got a piece (represented by y) moving down in the following

4|ooooo|
3|yyyox|
2|ooxxx|
1|xxxxx|
  12345

Simulate yyy moving down one spot. It then occupies (1,2), (2,2) and (3,2). Check your representation - 3,2 is occupied and so the block can't move there. This logic should (I think) apply to any shape piece on any placed board.

OTHER TIPS

Separate your behavioral logic from your view logic.

If you treat each Tetris piece as four blocks in your behavioral logic it becomes fairly trivial to do collision detection. There's no partials to detect as a block can't ever occupy some space between X and X+1. It's always one or the other. However once you've detected that X+1 isn't occupied and the piece will continue to fall it's simple to just add an animation that makes the piece appear to move from one space to the next with the animation completing at the same time as the logic dictates the piece has fallen by 1.

Yep, the best way to know where a figure should stop is to make an x-ray (2-d boolean array) of empty and full boxes.
But at the same time - you have to know which blocks of your figure to check for. If you're moving the figure down - you must check just the LOWER blocks of your figure. Do that by putting in separate categories - the blocks with unique horizontal values, and from there - determine which ones have the lowest vertical values. For a visual representation check this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top