I am afraid you are doing it wrong. The reason is that you are doing something ilegal. You are modifying the array of tiles inside the tile class.
Think about the Tile to be an object. Think about the array to be a container of the selected objects.
For your program:
- You create a container and defined what type of objects it will hold
- You create an object and add it to the container (Do this as many times as needed)
Now, if you want to access an object, you iterate through the array. If you need to remove an object, you can do it. However, it has to be done in the global scope and not inside the class.
Consider studying the following code. For OOP, check this tutorial.
Notice I am resizing the image right after I load them. This is more efficient that resizing the image every time it is drawn. It is a minor optimization at this point, but more for you to think about it.
Kf
final int UNDEFINED=-1;
int index=UNDEFINED;
//array of Tile objects
ArrayList <Tile> myTiles = new ArrayList <Tile>();
//also create a second array list to 'reset' from
ArrayList <Tile> newTiles = new ArrayList <Tile>();
void setup() {
background(0);
size(300, 300);
imageMode(CENTER);
textAlign(CENTER);
fillContainer();
}
void draw() {
background(0);
if (index!=UNDEFINED) {
myTiles.get(index).display();
} else {
textSize(35);
text("Random Fruits", width/2, height/3);
text("Click to play", width/2, 2*height/3);
}
}
void mouseClicked() {
if (index==UNDEFINED) {
background(0);
textSize(25);
text("Out of Names", width/2, height/3);
text("Click to Play Again", width/2, 2*height/3);
fillContainer();
index = int(random(myTiles.size()));
return; //Forces exiting the current function
}
if (myTiles.size() > 1) {
myTiles.remove(index);
index = int(random(myTiles.size()));
} else {
//THIS remove the last tile
myTiles.remove(index);
index=UNDEFINED;
}
}
void fillContainer() {
myTiles.clear();
PImage img;
img=loadImage("pic15.jpg");
img.resize(100, 100);
myTiles.add(new Tile("apple", img));
img=loadImage("pic16.jpg");
img.resize(100, 100);
myTiles.add(new Tile("orange", img));
img=loadImage("pic17.jpg");
img.resize(100, 100);
myTiles.add(new Tile("pear", img));
}
//Tile object
class Tile { //Tile knows an image and name
PImage img; //pulls in image
String item; //pulls in name
Tile(String tempItem, PImage tempImg) {//constructor
item = tempItem; //name pulled in
img = tempImg; //image pulled in
}
void display() {
background(0);
textSize(70);
fill(255, 0, 0);
text(item, width/2, 3*height/4);
image(img, width/2, height/4);
}
}