Overlapping JLabels in Tetris

60 Views Asked by At

So I'm trying to code Tetris in Java and I'm using JLabels for each piece. I'm using a Runnable timer to have the pieces move down, and then I use if statements with an executor to control when the piece should stop moving. The problem I have is how I should program the pieces so that when they interact with each other they stop moving down and trigger the executor shutdown. I know that I want to program the block to stop when the color that is a block ahead of it isn't black, signifying that there is a block there, but I need help figuring that out technically.

For Example:

Runnable timer = new Runnable() {


public void run() {

        if((825 - (piece.getSize().getHeight() + 40 + piece.getY()) < 1)) { 
            executor.shutdown();
            block();
            time();
        }
        else if(piece2 != null && (825 - (piece2.getSize().getHeight() + 40 + piece2.getY()) < 1)) {
            executor.shutdown();
            block();
            time();
        }
    }   
executor.scheduleAtFixedRate(timer, 2, 1, TimeUnit.SECONDS);
}

piece2 is referring to the other piece and is only used in shapes where I used to pieces to configure it.

I tried to make a block that tested the color in front of the other block but I had no way of doing that seeing as how I either only tested the background color or the color of the actual block. In which case I would need a way to adapt the block in front of the actual piece to the color that's present whether it be the background or the block, but I don't know how to do that.

1

There are 1 best solutions below

3
Hovercraft Full Of Eels On

Some suggestions:

  • Avoid using Swing components to represent a Tetris shape, use lighter-weight image sprites/shapes. There is no reason to use a JLabel, and this only makes your program slower, less responsive, harder to manage and more difficult to enhance.
  • Most importantly, the logic of the code should be separate from the GUI. You will want to create a non-GUI component TetrisBlock class that represents one Tetris block and then a TetrisShape class that holds a collection of TetrisBlocks. These should have x and y position fields, which are mutatable. This should also have collision detection by iterating through the collection of TetrisShapes held by your game object. When a collision is detected, then the animation should stop. Collision detection should be fairly easy with this set up since you are looking for collisions on a course granular scale, a block, and not a file scale since there are no real curves, just rectangles.
  • The GUI code should instead be updated by the timer to show a representation of the state of the non-GUI model.
  • You should be using a Swing Timer to drive the animation rather than a fixed rate executor service with a runnable. This won't solve the original problem but will help prevent future issues with code that currently breaks Swing threading rules.