Java How to get exact tile location in random tile engine

Posted by SYNYST3R1 on Stack Overflow See other posts from Stack Overflow or by SYNYST3R1
Published on 2012-04-08T05:27:16Z Indexed on 2012/04/08 5:28 UTC
Read the original article Hit count: 232

Filed under:
|
|
|
|

I am using the slick2d library. I want to know how to get the exact tile location so when I click on a tile it only changes that tile and not every tile on the screen.

My tile generation class

public Image[] tiles = new Image[3];
public int width, height;
public int[][] index;
public Image grass, dirt, selection;
boolean selected;
int mouseX, mouseY;

public void init() throws SlickException {
    grass = new Image("assets/tiles/grass.png");
    dirt = new Image("assets/tiles/dirt.png");
    selection = new Image("assets/tiles/selection.png");

    tiles[0] = grass;
    tiles[1] = dirt;

    width = 50;
    height = 50;

    index = new int[width][height];

    Random rand = new Random();
    for (int x = 0; x < width; x++)
    {
        for (int y = 0; y < height; y++)
        {
            index[x][y] = rand.nextInt(2);
        }
    }
}

public void update(GameContainer gc) {
    Input input = gc.getInput();
    mouseX = input.getMouseX();
    mouseY = input.getMouseY();

    if(input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON)) {
        selected = true;
    }
    else{
        selected = false;
    }
}

public void render() {
    for (int x = 0; x < width; x++)
    {
        for (int y = 0; y < height; y++)
        {
            tiles[index[x][y]].draw(x * 64, y *64);
            if(IsMouseInsideTile(x, y))
                selection.draw(x * 64, y * 64);
        }
    }
}

public boolean IsMouseInsideTile(int x, int y)
{
    return (mouseX >= x * 64 && mouseX <= (x + 1) * 64 &&
            mouseY >= y * 64 && mouseY <= (y + 1) * 64);
}

I have tried a couple different ways to change the tile I am clicking on, but I don't understand how to do it.

© Stack Overflow or respective owner

Related posts about java

Related posts about location