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

2017/3/26

Accessing Actor Method from World

rockon411 rockon411

2017/3/26

#
I have a method that adds selected actors to the world. Each time you add one you lose money. Each actor subclass has a different cost. I have a getCost() method that should return the cost, but I am not sure how to access it from the world subclass. This is in my world code.
public void onTouchDown(int x, int y)
    {
        System.out.println("You clicked on (" + x + ", " + y + ")");
        
        
        Actor bob = newActorOfSelectedType();
        add(bob, x, y);
        reduceMoney(getCost());
        
    }
public int reduceMoney(int spend)
    {
        total = total - spend;
        if(total <= 0)
        {
            return 0;
        }
        else
        {
            return total;
        }
    }
This is the getCost() method in my parent actor class.
protected int cost = 0;

public int getCost()
    {
        return cost;
    }
And heres an example of what I've put in my subclasses.
public Minnow()
    {
       cost = 3;
    }
Any help would be greatly appreciated
Super_Hippo Super_Hippo

2017/3/26

#
Change 'Actor' in line 6 to 'Minnow' (maybe also have to change the return type of your 'newActorOfSelectedType' method) and then you can use 'bob.getCost()' in line 8. I am not sure why your reduce method returns the money which is left. You should probably check first if it is possible to buy it (or you will end up with negative amount of money).
rockon411 rockon411

2017/3/26

#
I changed the Actor to Minnow and now I receive an error "incompatible types - found sofia.micro.Actor but expected Minnow"
danpost danpost

2017/3/26

#
Use the name of the parent actor class (where the 'getCost' method is located). For example, if the name of the class was Thing, then use:
Thing thing = (Thing) newActorOfSelectedType();
add(thing, x, y);
reduceMoney(thing.getCost());
rockon411 rockon411

2017/3/26

#
Thank you!
danpost danpost

2017/3/26

#
rockon411 wrote...
Thank you!
Hippo had a point about spending money that was not there. Better might be this:
Thing thing = (Thing) newActorOfSelectedType();
if (reduceMoney(thing.getCost()) < 0) reduceMoney(-thing.getCost());
else add(thing, x, y);
You need to login to post a reply.