简体   繁体   English

资源加载到ArrayList中,用于基于图块的游戏。 (JAVA)

[英]Resource loading into ArrayList for tile-based game. (Java)

So i'm attempting to develop a tile-based game using eclipse, and i have run into a problem on how to load the resources from the resource folder into an ArrayList. 因此,我试图使用Eclipse开发基于图块的游戏,并且在如何将资源从资源文件夹加载到ArrayList中时遇到了问题。 I have a file reader that can load all of the needed files into a list, but i can't use class folders for each tile type (grass, stone, etc) because an ArrayList can only store one class type. 我有一个文件读取器,可以将所有需要的文件加载到列表中,但是我不能为每种图块类型(草,石头等)使用类文件夹,因为ArrayList只能存储一种类类型。 Is there a way to load all sub-classes of the tile super-class into a single ArrayList. 有没有一种方法可以将tile超类的所有子类加载到单个ArrayList中。

If you have a parent class (or interface) that all of the other classes extend from, then you can simply use an ArrayList of that parent class. 如果您有一个其他所有类都从其扩展的父类(或接口),则只需使用该父类的ArrayList。 Just create an ArrayList of Tiles. 只需创建一个瓷砖的ArrayList。

List<Tile> tiles = new ArrayList<Tile>();

Tile a = new GrassTile(); //GrassTile extends Tile
Tile b = new StoneTile(); //StoneTile extends Tile

tiles.add(a);
tiles.add(b);

for(Tile t : tiles){
   t.doTileStuff();
}

Edit: You could also reconsider your design and try to favor composition over inheritance . 编辑:您还可以重新考虑您的设计,并尝试在继承方面偏爱合成 Instead of having a bunch of classes that extend Tile, have a single Tile class that contains attributes that determine how it behaves and looks. 与其拥有一堆扩展Tile的类,不如拥有一个包含确定其行为和外观的属性的Tile类。

如果要放入单个arraylist中的tile是超类的子类,则可以将arraylist设置为采用超类类型,同时将子类伪装成超类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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