This site requires JavaScript, please enable it in your browser!
Greenfoot back
RoverKnight
RoverKnight wrote ...

2021/4/13

How to get and delete an object that you click on?

RoverKnight RoverKnight

2021/4/13

#
Hey there! I'm trying to remake Minesweeper and trying to delete the "cover" block (undiscoveredCell) of the square that is clicked so as to reveal what's beneath. However, I don't know how to retrieve and subsequently delete the object that the mouse cursor is hovering over when clicking. I can't delete all actors from a given class, since the world is filled with a bunch of actors from the same class and I don't want all of them to be gone. Here's my current code:
MouseInfo mouse = Greenfoot.getMouseInfo();
        if (mouse != null)
        {
            int buttonNumber = mouse.getButton();
            if (buttonNumber == 1){
                getWorld().removeObject(getObjectsAt(mouse.getX(), mouse.getY(), undiscoveredCell.class));
            }
        }
I've tried using the getObjectsAt method as I've read about it online, but greenfoot doesn't recognize it ("cannot find symbol - method"). Am I maybe missing a library that I need to import, and am I even using the method correctly?
RcCookie RcCookie

2021/4/13

#
The problem is that getObjectsAt() returns a list of actors, as there may me multiple on that cell. What you can do is this:
import java.util.List; // at the very top

// in the method
List<UndiscoveredCell.class> onLoc = getWorld().getObjectsAt(mouse.getX(), mouse.getY(), UndiscoveredCell.class);
if(onLoc.size() > 0) // check that there actually is something there
    getWorld().removeObject(atLoc.get(0)); // removes the element that is the first in the list

// or
getWorld().removeObjects(getWorld().getObjectsAt(mouse.getX(), mouse.getY(), UndiscoveredCell.class));
Note that you also missed a getWorld() in line 6, or you must not have all those getWorld()s if the code is already located in your world class. In my opinion the easier way to go about this problem to let each UndiscoveredCell check for a mouse click on its own:
// in act of UndiscoveredCell 
if(Greenfoot.mouseClicked(this)) getWorld().removeObject(this);
This will remove the object when the mouse button is released. If you want the object to be removed instantly when the mouse is pressed down, replace „mouseClicked“ with „mousePressed“.
RoverKnight RoverKnight

2021/4/14

#
I implemented the code you wrote in the 2nd insert, and it works now. Thank you! I did put my original code in the cell covers act method, but forgot that I didn't need to then check which cell got clicked on... :,)
You need to login to post a reply.