-1

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?

4

1 回答 1

3

您在自身内部调用此方法,导致 StackOverflow 错误。

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

这是错误的方法。这应该在move()方法中。该moveTo方法获取一个位置并移动到该位置。这不应该被覆盖。

将其更改为:

public void move(Location newLocation)
{
    Location loc = new Location(getGrid().getNumCols(), getGrid().getNumRows());
    moveTo(loc);
    sideLength = 0;
}
于 2014-04-21T15:05:02.800 回答