简体   繁体   中英

How to manage hundreds of Entities efficiently?

OK so I am new am stuck on coming up with a good way of solving this problem. So I am creating an RPG top down survival game in Java using the slick2d. I have a problem when It comes to spawning items in the game. What is the best way to manage having hundreds of items... An example; I have a sub class of items called PickUpItems. For instance when a tree is destroyed by the player it spawns a PickUpItem which is just an Image with a Rectangle box for collision. What would be the best way to chose what Item to spawn without having to make hundreds of classes for each Interactive Item(Tree, bush, farming stuff etc). Should I have a item manager class? Given a name It will search a text file to get the parameters needed and create an Object then?

public void spawnPickUpItem(String type, int x, int y) { PickUpItem pickUpItem = null;

    switch(type)
    {
        case"Log":
            pickUpItem = new PickUpItem(type,logImage,x,y,this);
        break;
        case"Flint":
            pickUpItem = new PickUpItem(type,flintImage,x,y,this);
        break;
        case"Rock":
            pickUpItem = new PickUpItem(type,rockImage,x,y,this);
        break;
    }

This is my current attempt which works it spawns the necessary item but imagine running a switch statement with hundreds of cases each item you need an Item spawned in the game. I am sure some one can help.. THank you

You can follow the Factory Method pattern

Map<String, Image> imageRepository = new HashMap<>(); // to be filled

PickUpItem createItem(String type, int x, int y) {
    Image itemImage = imageRepository.getOrDefault(type, yourDefaultImg);
    return new PickUpItem(itemImage, x, y); 
}

public void spawnPickUpItem(String type, int x, int y) {
   PickUpItem pickUpItem = createItem(String type, int x, int y);
   // further logic . . .
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM