I need to create a tiled map nxn columns/lines. First,the program asks the user how many tiles he wants, then it creates a tiled map. After, the user clicks on one tile, and the tiles changes color. Then he clicks on anothe tile,and the color changes aswell. After that, the program will find a solution from the selected tile to the other.
FOR now, i created the tiled map with a Graphics2D component, but when i click on the tile,it's the whole graphic that changes color, not only one tile... Can you please tell me what's wrong? What is the great way of drawing a tiled map ? Thank you ! The maze should look like this:

I still need to enter the code of the walls and finding the solution. This is the code of my JPanel, where i create the map.
public LabyrintheInteractif (){
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
click=true;
repaint();
xClick=e.getX();
yClick=e.getY();
}
});
tiles=Integer.parseInt(JOptionPane.showInputDialog("How many tiles ?"));
Quadrilage", JOptionPane.YES_NO_OPTION);
setPreferredSize(new Dimension(734, 567));
setVisible(true);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.white);
rect = new Rectangle2D.Double(0, 0,getWidth(), getWidth());
g2d.fill(rect);
g2d.setColor(Color.black);
for (row = 0; row <tuiles; row++) {
for (column = 0; column < tuiles; column++) {
g2d.setStroke(new BasicStroke(3));
g2d.draw( square=new Rectangle2D.Double(column*100 , row*100,100,100));
}
if(click){
g2d.setColor(Color.green);
g2d.fill(square);
repaint();
}
}
The problem here is that you are not checking for which tile the user has clicked on. Instead you are just checking to see whether or not he user has clicked at all.
What you need to do is find the width and height of the tiles.
Then you need to check for which tile the user has clicked on in the nested for loop kind of like so.
for (row = 0; row <tuiles; row++) {
for (column= 0; column<tuiles; column++) {
if(clicked){
//check if the click x position is within the bounds of this tile
if(column * tileWidth + tileWidth > xClick && column * tileWidth < xClick){
//check if the click y position is within the bounds of this tile
if(row * tileHeight + tileHeight > yClick && row * tileHeight < yClick){
//mark this tile as being clicked on.
clicked = false;
}
}
}
}
}
Then you will need to store boolean values that will state whether or not a particular tile has been clicked on. That way when you draw the tile you can use something like this:
if(thisTileHasBeenClicked){
//if the tile has been clicked on
g2d.setColor(Color.green);
g2d.fill(square);
}else{
//if the tile has not been clicked on
g2d.setColor(Color.gray);
g2d.fill(square);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With