如何有效管理数百个实体?

问题描述 投票:0回答:1

好,所以我是新手,一直想出一种解决此问题的好方法。因此,我正在使用slick2d用Java创建一个RPG自上而下的生存游戏。在生成游戏中的物品时,我遇到了问题。管理数百个项目的最佳方法是什么?我有一个子类,称为PickUpItems。例如,当一棵树被玩家摧毁时,它会生成一个PickUpItem,它只是一个带有矩形框的图像用于碰撞。什么是最好的方法来选择要生成的物品,而不必为每个交互式物品(树,灌木,农作物等)建立数百个类。我应该参加项目经理班吗?给定名称它将搜索一个文本文件以获取所需的参数并创建一个Object呢?

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;
    }

这是我目前的尝试,它能够生成必要的物品,但可以想象一下,运行一个带有数百种情况的switch语句,您需要在游戏中生成一个物品。我相信有人可以帮忙。谢谢您

java resources lwjgl slick2d
1个回答
0
投票

您可以遵循Factory Method模式

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 . . .
}
© www.soinside.com 2019 - 2024. All rights reserved.