2014-04-01 40 views
0

我將如何檢查錯誤類前面的兩個空格是否爲空,並且不會超出邊界?現在,這是我所擁有的檢查網格世界中的位置

public void act() 
{ 
    if(canMove()) 
    { 
    Location loc = getLocation(); 
    Location nextLocation = loc.getAdjacentLocation(getDirection()); 
    nextLocation = nextLocation.getAdjacentLocation(getDirection()); 
    if (nextLocation == null) 
    { 
     move(); 
     move(); 
    } 

    } 
} 

這似乎不工作,因爲該錯誤什麼都不做。

回答

0

你可能意思是if(nextLocation != null)。我們不希望這個bug跳出板子(到null空間)。這是從我記憶中的GridWorld;我手邊沒有這個程序。

+0

的錯誤現在移動,但我怎麼把它留在界格? – Hulu

0

你有什麼有兩個問題。

  1. 不檢查的下一個位置是在網格,你知道
  2. 沒有動,你發現的位置。 Move()只是在當前方向上移動,而不管它是否在網格中。所以調用它兩次前進兩次,但沒有使用您發現的位置在網格中。

嘗試量變到質變您的代碼:

 public void act() 
     { 
      if(canMove()) 
      { 
       Location loc = getLocation(); 
       Location nextLocation = loc.getAdjacentLocation(getDirection()); 
       nextLocation = nextLocation.getAdjacentLocation(getDirection()); 
       Grid<Actor> gr = getGrid(); 

       if (gr.isValid(nextLocation)) 
       { 
        moveTo(nextLocation); 
       } 
       else 
        move(); //This could be move() so you only move forward one 
          //space or turn() to turn 

      } 
     }