5

I was making a game with XNA game studio and now I want to rewrite it in Java. It's something like a 2D Minecraft clone. For collision detection, I have to loop through all blocks in the game to check on whether the player is colliding with a block. With a huge number of blocks, it is impossible to do so, so I made a grid system. I divided the world into grids which contain blocks, and put them into a dictionary.

Dictionary<string, List<Block>> gameBlocks;

Now I have only to loop through the blocks in the current grid.

This is the method to register a block:

public void RegisterBlock(Block block)
{
    idX = (int)(block.blockPosition.X / width);
    idY = (int)(block.blockPosition.Y / height);
    string id = idX.ToString() + "_" + idY.ToString();
    if (gameBlocks.ContainsKey(id))
    {
        gameBlocks[id].Add(block);
    }
    else
    {
        gameBlocks.Add(id, new List<Block>());
        gameBlocks[id].Add(block);
    }
}

Now I am trying to rewrite it in Java but I don't know how to put something into a Dictionary.

4

2 回答 2

8

使用 Java 的Map接口和HashMap类。您的方法在 Java 中看起来像这样:

private Map<String, List<Block>> gameBlocks = new HashMap<String, List<Block>>(); // Java 6
// OR:
private Map<String, List<Block>> gameBlocks = new HashMap<>(); // Java 7

public void registerBlock(Block block) {
    idX = (int)(block.blockPosition.X / width);
    idY = (int)(block.blockPosition.Y / height);
    String id = idX + "_" + idY;
    if (gameBlocks.containsKey(id)) {
        gameBlocks.get(id).add(block);
    } else {
        gameBlocks.put(id, new ArrayList<Block>());
        gameBlocks.get(id).add(block);
    }
}

请注意我对 Java 推荐的格式/命名样式所做的一些更正。

于 2012-10-15T19:46:58.547 回答
0

Java has something called HashMap which may be useful for you. Here is documentation for HashMap.

Example:

HashMap<string, List<Block>> 
于 2012-10-15T19:35:41.767 回答