Java: What is a good data structure for storing a coordinate map for an infinite game world?

前端 未结 11 1303
心在旅途
心在旅途 2020-12-23 11:35

I am used to coding in PHP but I am not really proficient with Java and this has been a problem for some time now. I expect it to be a fairly easy solution, however I cannot

11条回答
  •  离开以前
    2020-12-23 11:58

    I came to this thread with the same problem, but my solution was to use Map/HashMaps, but these are one dimensional.

    To overcome this, instead of using a map within a map (which would be messy and very inefficient) I used a generic Pair class (not something that you'll find in the stock java library) although you could replace this with a Position class (virtually the same code, but not generic, instead integers or floats).

    So when defining the map: Map tiles = new HashMap;

    For placing tile objects onto the map I used tiles.put(new Pair(x, y), new GrassTile()); and for retrieving the object tiles.get(new Pair(x, y));.

    [x/y would be any coordinate you wish to place (this allows negative coordinates without any mess!), "new GrassTile()" is just an example of placing a tile of a certain type during map creation. Obviously - as previously stated - the Pair class is replacable.]

    Why not ArrayLists you may ask? Because array lists are much more linear than mapping, and in my opinion are more difficult to add and retrieve tiles, especially on 2 Dimensions.

    Update:

    For anyone wondering why there isn't a Pair() class in Java, here's an explanation.

提交回复
热议问题