0

I am trying to implement the Game Pac-Man and I am having a bug that I know is wrong, but I do not know how to fix. I am using a generic Pellet class that has two subtypes, smallPellet and energizerPellet. I have a intersects method that will tell if Pac-Man's location is the same. I have stored the instances of pellet on my map in a set so there are no repeats, but I am think my implementation of the compareTo override method is wrong. Each pellet has a pos_x and pos_y that are different for each pellet and I am trying to differentiate each pellet using those two factors, but when I implement it, sometimes they are not removed from the set when I go over them. Any help would be appreciated!

@Override
public int compareTo(Pellet pellet) {
    // TODO Auto-generated method stub
    if (pellet == null) {
        throw new NullPointerException();
    }
    if (this.pos_x == pellet.pos_x && this.pos_y == pellet.pos_y) {
        return 0;
    } else if ((this.pos_x^2 + this.pos_y^2) < (pellet.pos_x^2 + pellet.pos_y^2)) {
        return -1;
    } else {
        return 1;
    }
}

And my Background Class (JPanel) methods that are related:

public static Set<SmallPellet> smallPellet() {
    Set<SmallPellet> pellets = new TreeSet<>();
    for (int i = 1; i < width; i++) {
        for (int j = 1; j < height; j++) {
            if (map[j][i] == 0) {
                pellets.add(new SmallPellet(10*i, 10*j));
            }
        }
    }
    System.out.println(pellets.size());
    return pellets;
}

Set<SmallPellet> smallPellets = new TreeSet<>(smallPellet());

Removing them when intersecting:

Set<SmallPellet> smPellets = new TreeSet<>(smallPellets);
        for (SmallPellet pellet : smallPellets) {
            if (pellet.intersects(pacman)) {
                smPellets.remove(pellet);
                score += 10;
                scoreLabel.setText("Score: " + score);
            }
        }
        smallPellets = smPellets;

I think my problem in comparing is that when comparing 5,7 and 7,5 obviously they are not equal, but which one is greater and which one is less than than the other? When I put them in a set, Set.remove(a) is confused where to find it and remove it when it is close to a similar number.

Anonymous
  • 13
  • 3
  • Ordering has to be absolute, so comparing distance is not good, since that is a relative measure. You could sort by X, then by Y. That would be an absolute order. But why sort at all, i.e. why use `TreeSet`? Use `HashSet` and implement `equals()` and `hashCode()` on X and Y, since all you care about is equality, not "order". – Andreas Apr 23 '16 at 18:52
  • http://stackoverflow.com/questions/1991380/what-does-the-operator-do-in-java – Radiodef Apr 23 '16 at 19:05

0 Answers0