Pergunta

UPDATE: All I need answered is the question at the bottom.

This is a special type of SpiralBug so I haven't seen any examples of this on the internet. This SpiralBug uses the SpiralBug code but it has extras to it, once it gets to it's border of a BoundedGrid and cannot move forward anymore it has to restart at the center of the grid again, this is where my problems begin. Here is my code there are no errors.

My code for SpiralBugRunner

    import info.gridworld.actor.ActorWorld; 
    import info.gridworld.grid.Location; 
    import java.awt.Color; 

    public class SpiralBugRunner 
     { 
      public static void main( String args[] ) 
      { 
      ActorWorld world = new ActorWorld( ); 
      SpiralBug bug1 = new SpiralBug(0);

      world.add (new Location(4, 4), bug1 );

      world.show( ); 
      } 
     }

and for SpiralBug

import info.gridworld.actor.Bug;
import info.gridworld.actor.Actor;
import info.gridworld.grid.Location;

public class SpiralBug extends Bug 
 { 
  private int sideLength; 
  private int steps; 

  public SpiralBug(int n) 
  { 
    sideLength = n; 
    steps = 0; 
  }

  public void act() 
  { 
   if (steps < sideLength && canMove()) 
   { 
    move(); 
    steps++; 
   } 
    else 
   { 
    turn(); 
    turn(); 
    steps = 0; 
    sideLength++; 
   }  
  }

 public void moveTo(Location newLocation)
  {
   Location loc = new Location(getGrid().getNumCols(), getGrid().getNumRows());
   moveTo(loc);
   sideLength = 0;
  }
 }  

My real question is what should I do to set to reset the bug to the middle to run it again after it cannot move?

Foi útil?

Solução

You're calling this method within itself, causing a StackOverflow error.

public void moveTo(Location newLocation)
{
    Location loc = new Location(getGrid().getNumCols(), getGrid().getNumRows());
    moveTo(loc);
    sideLength = 0;
}

This is the wrong method. This should be in the move() method. The moveTo method takes a location and moves to that location. This should not be overriden.

Change it to:

public void move(Location newLocation)
{
    Location loc = new Location(getGrid().getNumCols(), getGrid().getNumRows());
    moveTo(loc);
    sideLength = 0;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top