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

2013/10/3

Help, coding issues.

luigidude125 luigidude125

2013/10/3

#
I need to make a game for my Computer Science course and I need a bit of help with one part. I have all the code set up properly (or at least it looks (and compiles) properly). However, I have a princess class and a guard class. I am trying to make it so the guard moves but not very far from the princess (who is immobilized). I thought I had it set up but, for some reason, the guard stays on the princess and goes back and forth on her (doesn't move more than maybe 1 grid space from her). Here is what I have regarding the Guard's actions:
    public boolean isPrincessNear()
    {
        return getObjectsInRange(200, Princess.class).isEmpty();
    }
    public void guard()
    {
        if(isPrincessNear())
        {
            randomTurn();
            move(3);
        }
        else
        {
            turnTowards(560, 560);
            move(10);
        }
    }
er, the code that's relevant (there's also code telling him to kill people who he touches (other than her)). (560, 560) is the princess' location which is why I have him facing there if he ever can't find her in his radius. If you could help me with this, that would make me a good bit happier, if not, I can probably tell the teacher I couldn't resolve the issue when I turn it in (in 5 days). Anyhow, thanks for at least bothering to read it.
danpost danpost

2013/10/3

#
I believe you need to return the opposite case in the 'isPrincessNear' method. If the list of Princess objects within the radius given is empty, then she is NOT near.
luigidude125 luigidude125

2013/10/4

#
thanks dan , this is what it looked like in the end:
    public boolean isPrincessNear()
    {
        if (getObjectsInRange(200, Princess.class).isEmpty())
            return false;
        else
            return true;
    }
    public void guard()
    {
        if(isPrincessNear())
        {
            randomTurn();
            move(3);
        }
        else
        {
            turnTowards(560, 560);
            move(10);
        }
    }
I used an if statement cause I couldn't figure out where to put the "not" (!) in the code.
bourne bourne

2013/10/4

#
If you want to return false when the following is true (as well as the opposite, i.e. return true when is false) getObjectsInRange(200, Princess.class).isEmpty() Then return that with a "not" (!) at the front of it Like the following: return !getObjectsInRange(200, Princess.class).isEmpty();
You need to login to post a reply.