Search code examples
javatetris

Tetris - fix hard drop collision


I am writing a method to handle direction for Tetris and am confused about the logic to write hard drop. the move method is called whenever a key is pressed.

public void move(Direction direction) {
    if (canMove(direction)) {
        switch (direction) {
        case DOWN:
            row = row + 1;
            break;
        case LEFT:
            col = col - 1;
            break;
        case RIGHT:
            col = col + 1;
            break;  
        case DROP:
            for(int i = row; i < Grid.HEIGHT; i ++){
                if(!grid.isSet(i,col)){
                    row =  row + 1;
                }       
            }
            break;
        }
    }
}

My idea is to find the furthest open space where the block can hard drop and it will repeat going down rows until it hits that space to hard drop.

Edit: This is my canMove method and I've changed my case drop, instant drop does work, however, there seems to be a problem with collision when drop key is used. I dont quite understand why

public boolean canMove(Direction direction) {
    if (!ableToMove)
        return false;

    boolean move = true;
    // if the given direction is blocked, we can't move
    // remember to check the edges of the grid
    switch (direction) {
    case DOWN:
        if (row == (Grid.HEIGHT - 1) || grid.isSet(row + 1, col))
            move = false;
        break;

    case DROP:
        if (row == (Grid.HEIGHT - 1) || grid.isSet(row + 1, col))
            move = false;
        break;  
    // currently doesn't support checking LEFT or RIGHT
    // MODIFY so that it correctly returns if it can move left or right
    case LEFT:
        if (col == (0) || grid.isSet(row, col-1))
            move = false;
        break;

    case RIGHT:
        if (row == (Grid.WIDTH - 1) || grid.isSet(row, col+1))
            move = false;
        break;


    }
    return move;
}

Solution

  • The required change in DROPcase is

    case DROP:
            while(canMove(DOWN)){
                row =  row + 1;  
            }
            break;