instead of trying to identify the drawing order for each sprite itself you should create a proper drawing order first of.
List<Sprite> sprites;
Comparator<Sprite> topLeftComparator;
void draw(Graphics graphics){
sprites.sort(topLeftComparator); //create proper drawing order first
for (Sprite sprite: sprites){
sprite.draw(graphics); //then draw all sprites
}
}
Details
let's assume you have a class (better: an interface) named Sprite. That Sprite allows you to set the position of the sprite (and read it back) and to draw it
interface Sprite {
//set & read back position
void setPostion(int x, int y);
int getX();
int getY();
//draw
void draw(Graphics graphics);
}
you can now create and position all Sprites that you want to draw. Add them to your list:
Sprite tree, player;
List<Sprite> sprites;
...
//set postion
tree setPosition(2,4);
player.setPosition(2,3);
//and add to the list
sprites.add(tree);
sprites.add(player);
then you simply sort that list and draw your sprites according to the order of the list (as mentioned above).
Sorting
the magic happens when you sort the list. The sorting algorithm that is used sorts the sprites first by y-value (aka each row) and than by x-value (by column). That results in an top/left->bottom/right order.
Comparator<Sprite> topLeftComparator = new Comparator<Sprite>() {
@Override
public int compare(Sprite s1, Sprite s2) {
int compareValueOfRow = Integer.compare(s1.getY(), s2.getY());
if (compareValue == 0){ //0 means y is equal for both
//the return according to x-pos
return Integer.compare(s1.getX(), s2.getX());
}else{
return compareValue;
}
}
};