Swapping tile sometimes not working [Bugs]

I did a little clean up and change the code to make it shorter. I just want to swap the tile if and only if they are consecutive to each other but not in the diagonals. I used a different one before and it works fine. Please help.

Here's the code:

Game class

private Tile tile1,tile2;
private Vector v1;

public void mousePressed(MouseEvent e) {
    v1 = new Vector(e.getX(),e.getY());
    if(tile1 == null && tile2 == null) {
        tile1 = grid.getTile(v1.y / tileSize,v1.x / tileSize);
    }else if(tile1 != null) {
        tile2 = grid.getTile(v1.y / tileSize,v1.x / tileSize);
        if(tile1.canSwap(tile2)) {
            System.out.println("Swapping " + tile1 + " with " + tile2);
        tile1 = tile2 = null;

Tile class

public boolean canSwap(Tile other) {
    int dr = Math.abs(row - other.row);
    int dc = Math.abs(col - other.col);
    return (dr == 1 && dc == 0) || (dc == 1 && dr == 0);

public void swap(Tile other) {
    Tile temp = Tile.copy(this);
    this.row = other.row;
    this.col = other.col;
    this.candy = other.candy;
    other.row = temp.row;
    other.col = temp.col;
    other.candy = temp.candy;

I don't get what's wrong with my code. Sometimes it work though. You can check all my source code on my GitHub


  • edited November 2017

    And please check this too. Maybe you can solve that problem of mine. :D

  • this is a processing forum. i see a java project...

  • But it's the same Java right. I think somebody could help :-S

  • with a processing project i can take your code and paste it into my pde editor and it'll run

    with your java i have to work out how to compile and run it. you've not provided anything like a makefile or a pom so i can't run your code. if i can run it, i can't debug it.

  • @xxMrPHDxx If it should be easy to make an MCVE from this, could you do it please?

  • edited November 2017

    It's an eclipse project. I think you can simply pull it off from my repository and run the code, am I right? Or maybe you guys know some forum I can ask about general java code?

  • Thank you @GoToLoop for the link. Anyway, I have found the problem with my code.

    I shouldn't interchange the row and col of the tiles.

    Like this:

    public void swap(Tile other){
        Tile temp = Tile.copy(this);
        this.candy = other.candy;
        other.candy = temp.candy;

    I just need to change the candy between the two tiles. My mistake :D

Sign In or Register to comment.