Question

I am trying to solve an instance of Blockworld Problem. Basically an NxN Grid contains Blocks A, B, C and an Agent. Only the Agent can move, if on the way it encounter a Block, then their positions will be switched. For example, Agent(1, 0) goes left encounter a Block B(0, 0) then the new positions of the two would be Agent(0, 0) and B(1, 0).

Both my Agent and Block classes are subclass of Entity.

Here is my function swap(). It checks if after a move, the Agent is on the a Block, then the new Position of Block would be the previous position of the Agent.

I tried with (Block block : blockList) and it works, but not with the (Entity en : entityList) when I tried to use Polymorphism.

Can anyone spot the mistake I made please?

public void swap() {

    for (Entity en : entityList) {
        if (agent.position.equals(block.position) && (en instanceof Block))  {
            System.out.print("Agent overlap block: " + en);
            en.previousPosition = new Dimension(block.position.width, block.position.height);
            en.setPosition(agent.previousPosition); 
        }
    }
}
Was it helpful?

Solution

First Of All, you haven't told where did the "block" in the if statement came from. What you may need to do, is:

public void swap(){
    for(Entity en:entityList){
        if((en instanceof Block)&&(en.position.equals(agent.position)){
                    //                 ^here is "en" instead of block
            System.out.println("Agent overlab block: "+en);
            en.previousPosition=new Dimension(
                    en.position.width,
                    en.position.height);
            en.setPosition(agent.previousPosition);
        }
    }
}

At last, you may use java.awt.Point instead of Dimension. Also, you should use setter method for the field "previousPosition".

OTHER TIPS

Your problem is that your code does stuff if agent.position and block.position are equal; but in the example you talk about, agent.position and block.position are different. So your code is never actually making any changes.

Everywhere you use the block variable in the function, you need to change it with en since your for loop no longer creates a variable named block.

When you move entities around in this function, be careful that you don't accidentally try to swap the agent with itself!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top