Search code examples
javacollision-detection

Collision detection only working on the last placed piece


I have been making a simple tetris game to enhance my java skills and here are the two classes:

import java.awt.*;
import java.util.ArrayList;

public class Piece{
    int posX;
    int posY;

    boolean controllable;

    Rectangle pixel;
    Rectangle leftBorder = new Rectangle(0,0,20, 400);
    Rectangle rightBorder = new Rectangle(180, 0, 20,400);
    Rectangle bottomBorder = new Rectangle(0, 300, 200, 20);

    ArrayList<Rectangle> boardPieces = new ArrayList<>();

    //constructor
    public Piece(){
        spawnNew();
    }

    public int getPosX(){
        return pixel.x;
    }

    public int getPosY(){
        return pixel.y;
    }

    public void createPixel(){
        pixel = new Rectangle(posX*20, posY*20, 20, 20);
    }

    public void drawPixel(Graphics g, Rectangle r){
        Graphics2D g2D = (Graphics2D) g;
        g2D.fill(r);
    }

    public void spawnNew(){
        if (pixel != null){
            boardPieces.add(new Rectangle(getPosX(), getPosY(), 20, 20));
        }

        controllable = true;
        posX = 3;
        posY = 0;
        createPixel();
    }

    public void move(char c, String s){
        if(controllable){
            switch (c){
                //go in x direction
                case 'x':
                    if(s.equals("+")){//right
                        posX ++;
                        createPixel();
                        if(detectCollision(rightBorder) || detectCollision()){
                            posX --;
                            createPixel();
                        }
                    }else{//left
                        posX --;
                        createPixel();
                        if(detectCollision(leftBorder) || detectCollision()){
                            posX ++;
                            createPixel();
                        }
                    }
                    break;
                //go in y direction
                case 'y':
                    if(s.equals("+")){//down
                        posY ++;
                        createPixel();
                        if(detectCollision(bottomBorder) || detectCollision()){
                            posY--;
                            controllable = false;
                            createPixel();
                        }
                    }else{//up
                        posY --;
                        createPixel();
                    }
                    break;
            }
        }
    }

    public boolean detectCollision(Rectangle r){
        return pixel.intersects(r);
    }

    public boolean detectCollision(){
        boolean collision = false;
        for (Rectangle boardPiece : boardPieces) {
            if (boardPiece != null) {
                collision = pixel.intersects(boardPiece);
            }
        }
        System.out.println(boardPieces.toString());
        return collision;

    }
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class GamePanel extends JPanel implements KeyListener{
    Piece piece;

    //constructor
    public GamePanel() {
        piece = new Piece();
        //set panel attributes
        this.setPreferredSize(new Dimension(200, 400));
        this.addKeyListener(this);
        this.setFocusable(true);
        this.requestFocusInWindow();

        //create timer
        Timer fallTimer = new Timer(500, _-> {
            piece.move('y', "+");
            if(!piece.controllable){
                piece.createPixel();
                piece.spawnNew();
            }
            repaint();
        });
        fallTimer.start();
    }

    @Override
    public void paintComponent(Graphics g){
        //clear background
        super.paintComponent(g);


        g.setColor(Color.black);
        piece.drawPixel(g, piece.pixel);

        g.setColor(Color.green);
        for (Rectangle i: piece.boardPieces){
            if (i != null) {
                piece.drawPixel(g, i);
            }
        }

        g.setColor(Color.red);
        piece.drawPixel(g, piece.bottomBorder);
        piece.drawPixel(g, piece.leftBorder);
        piece.drawPixel(g, piece.rightBorder);
    }

    //empty
    @Override
    public void keyTyped(KeyEvent e) {}

    @Override
    public void keyPressed(KeyEvent e) {
        switch (e.getKeyCode()){
            //"a"
            case 65:
                piece.move('x', "-");
                repaint();
                break;
            //"d"
            case 68:
                piece.move('x', "+");
                repaint();
                break;
            //"s"
            case 83:
                piece.move('y', "+");
                if(!piece.controllable){
                    piece.spawnNew();
                }
                repaint();
                break;
            //"space"
            case 32:
            while(piece.controllable){
                piece.move('y', "+");
            }
            repaint();
            if(!piece.controllable){
                piece.spawnNew();
            }
            repaint();
            break;
        }

    }

    //get key codes
    @Override
    public void keyReleased(KeyEvent e) {
        this.requestFocusInWindow();
        System.out.printf("%c: %d\n", e.getKeyChar(), e.getKeyCode());
    }
}

I also have a frame class but that only has a few lines such as frame.pack() and frame.add(panel)... I'd prefer you wouldn't comment on the efficiency of my code since I'm trying to tackle every problem by living and solving them myself. But if you have any critical and constructive opinions about how I should change my code, I wouldn't say no.

for some reason, my collision detection only works on the very last placed piece instead of all of the boardPieces. I tried using the .toArray() method of the ArrayList class just in case that arraylists might be the issue but that didn't work.


Solution

  • This should basically be a comment, but it's a bit long. In your detectCollision() method, you iterate over the list of board pieces, and then return the last value of that test. In other words, you overwrite the value of the collision detection each loop, so you only get the last value in the list.

    public boolean detectCollision(){
        boolean collision = false;
        for (Rectangle boardPiece : boardPieces) {
            if (boardPiece != null) {
                // This overwrites the previous value
                collision = pixel.intersects(boardPiece);
            }
        }
        System.out.println(boardPieces.toString());
        return collision;
    
    }
    

    Fix this by returning a collision immediately:

                if( pixel.intersects(boardPiece) ) return true;
    

    Or by accumulating the value so it is not overwritting.

                collision |= pixel.intersects(boardPiece);