This site requires JavaScript, please enable it in your browser!
Greenfoot back
Giantpotato
Giantpotato wrote ...

2016/6/21

How to change a class name using arrays...?

Giantpotato Giantpotato

2016/6/21

#
The title may be a bit misleading (or not even make sense) because I have no idea how to describe it. When it says "addObject(new Tile(), 5, 5);", I want 'Tile' to become 'RedTile' or 'GreenTile' depending on what 'i' is. Is this possible?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class MyWorld extends World
 
{
    public int HowManyPerRow = 160;
    public int HowManyPerColumn = 90;
    public MyWorld()
    {   
        // Create a new world with 1700x900 cells with a cell size of 1x1 pixels.
        super(1600, 900, 1); //1737 x 949 = Max res (for me)
        gen();
    }
    public void gen()
    {
       int e = 0;
       String tiles[] = new String[2]; // Creates an array with a size of 3
       for(int i = 0; i < 2; i++) // Assigns the values of the array to RGB
       {
           if(i == 0)
           {
               tiles[i] = ("Red");      //tiles[i(0)] = Red
           }
           else if(i == 1)
           {
               tiles[i] = ("Green");    //tiles[i(1)] = Green
           }
           else if(i == 2)
           {
               tiles[i] = ("Blue");     //tiles[i(2)] = Blue
           }
           e++;
       }
       for(int q = 0; q < HowManyPerRow - 1; q++)  
       {
           addObject(new Tile(), 5, 5);
       }
danpost danpost

2016/6/21

#
It would be better to have just one Tile class (not using 'RedTile', 'GreenTile' and 'BlueTile'). Then have the constructor of the Tile class set the appropriate image depending on the String given it:
1
2
Actor tile = new Tile(tiles[i]);
addObject(tile, 5, 5);
The constructor could be something like this:
1
2
3
4
public Tile(String color)
{
    setImage(color.toLowerCase()+"Tile.png");
}
where the images have the filenames "redTile.png", "greenTile.png" and "blueTile.png".
valdes valdes

2016/6/21

#
I don't really understand the logic of your code, but I can answer your main question.
1
2
3
4
5
6
7
8
Actor tile;
switch (i) { // i has values between 0 and 2
  case 0: tile = new RedTile(); break;
  case 1: tile = new BlueTile(); break;
  default: tile = new GreenTile(); break;
}
...
addObject(tile, x, y);
NOTE:
1
String tiles[] = new String[2];
doesn't create an array of size 3, is size 2.
1
tiles[2]
will generate an IndexOutOfBoundsException
You need to login to post a reply.