I am working on a tile based game, where various tiles have different states. I am now looking to add a player object, this object will continually check the states of the tiles in order to move.
My Tile class:
class Tile {
int x, y;
boolean empty = true;
boolean baseCell = true;
boolean active = false;
public static final int EMPTY = 0;
public static final int BASE = 1;
public static final int ACTIVE = 2;
Tile(int x_, int y_, boolean baseCell_) {
x=x_;
y=y_;
baseCell=baseCell_;
}
void display() {
if (baseCell) {
fill(0, 0, 255);
} else {
if (empty) {
fill (255);
} else if (active) {
fill(255, 100, 50);
}
}
stroke(0);
rect(x, y, 50, 50);
}
}
When the game starts, 4 baseCells are drawn and cannot be changed. The user is able to click on other cells to change their values from empty to active or active to empty.
Currently I am unsure how to assign booleans the static values I have set - or perhaps this is not the best approach.
Any help or guidance would be much appreciated.
First of all, given that you want to assign to boolean values, the values of the static variables, I would say that it would be impossible since ACTIVE = 2. This value cannot be used as a boolean since it is not 0 nor 1.So if you want to use boolean variables all static final variable values should be 0 or 1.
Secondly, you should consider gathering all the constants (static final variables) in an interface which will be implemented by each class that needs one of those constants. It is a better programming practice and this will help you organize your project better.
Finally, if you want to change the value of the variables empty,active,baseCell, you should either include them in the constructor like so:
and/or you should implement getters and setters for each one of them like so:
And the way to change the respective values is by simply calling either the constructor, when the object is first constructed, and the setters after that like so:
Final notes: Regarding the visibility of the setter you should be careful, because if you make it public, anyone can access it and change its' value, and this affects the security of your application. The way to tackle this is through the hierarchy.
I suggest you read this: http://docs.oracle.com/javaee/6/tutorial/doc/gjbbp.html (basic info on getters/setters) and this: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html (required knowledge to tackle the setter problem)
As I was mentioning in the commend, rather than using a boolean for each state, you can use a single integer to keep track of the cell state. This will also allow you to use a switch statement. There's nothing wrong with if/else, you can achieve the same thing, but it may help things tidy.
Here's a basic proof of the above concept based mostly on your existing code:
Later on you may choose to call functions from within the switch statements to keep the code easier to manage (especially if you might use many states)