2016-11-15 45 views
0

我正在創建一個獨立城市建築遊戲,我試圖編寫一個系統來檢查供水是否已在4X4的集合瓷磚內構建。AS3數組TileMap檢查?

var blankMap: Array = [{0, 0, 0, 0, 0, 1, 0, 0, 0, 0}, 
         {0, 0, 0, 0, 0, 1, 0, 0, 0, 0}, 
         {0, 0, 0, 0, 0, 1, 0, 0, 0, 0}, 
         {0, 0, 0, 2, 0, 0, 2, 0, 0, 2}, 
         {0, 0, 8, 0, 0, 0, 0, 0, 0, 0}, 
         {0, 0, 0, 0, 0, 0, 0, 0, 2, 0}, 
         {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}]; 

public function checkWater(mY, mX): void { 
     // LEFT 
     if (blankMap[mY][mX - 1] == 8) { 
      trace("resource found left"); 
     } 
     if (blankMap[mY][mX - 2] == 8) { 
      trace("resource found left"); 
     } 
     if (blankMap[mY][mX - 3] == 8) { 
      trace("resource found left"); 
     } 
     if (blankMap[mY][mX - 4] == 8) { 
      trace("resource found left"); 
     } 
} 

// RIGHT 
if (blankMap[mY][mX + 1] == 8) { 
      trace("resource found right"); 
     } 
     if (blankMap[mY][mX + 2] == 8) { 
      trace("resource found right"); 
     } 
     if (blankMap[mY][mX + 3] == 8) { 
      trace("resource found right"); 
     } 
     if (blankMap[mY][mX + 4] == 8) { 
      trace("resource found right"); 
     } 

該系統的工作原理,但只適用於東,南,西,北。有沒有更簡單的方法來做到這一點?它只會檢查瓷磚地圖上1,2,3和4個瓷磚是否包含供水....這是瓷磚地圖上的數字8。 mY和mX是被點擊的圖塊的位置。

任何建議都會很棒。我基本上需要能夠檢查NUMBER 8而不是0的瓦片區域/瓦片地圖(4X4最大距離),這意味着瓦片是草地。這聽起來很容易,我確信它是這樣,我無法理解這個數學。謝謝。

+2

對於循環,while循環,遞歸函數將所有的工作。 [文檔for循環](http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3_Flex/WS5b3ccc516d4fbf351e63e3d118a9b90204-7fcf.html) – DodgerThud

+1

而就提示,你應該檢查是否你走出界限在你的功能中操作的座標。在你的示例代碼中,如果你的地圖只有7的高度,但你總共運行了8個(開始座標爲+1),那麼當你嘗試檢查南或北時,你總是會遇到錯誤。 – DodgerThud

回答

0

你的blankMap看起來不錯 - 它應該是一個數組數組?像

private var blankMap:Array = [[0, 0, 0, 0, 0, 1, 0, 0, 0, 0] ... 

正如DodgerThud已經提到的,你還需要檢查如果座標地圖內,否則你會碰到一個索引越界異常。我會做的一般方法,以便您可以檢查是否有資源是在一個特定的範圍,否則,你需要寫自己的職能的一切:

// check if there is a water supply within 3 tiles starting at x = 3, y = 1 
var waterSupplyExists:Boolean = checkForResourceWithinReach(3, 1, 8, 3); 

// startX is the x coordinate of your tile that was clicked 
// startY is the y coordinate of your tile that was clicked 
// resource is th eresource to look for (8 = water supply) 
// reach is the distance to look for. 3 would mean we look 3 tiles away around your start tile (7x7 square) 
public function checkForResourceWithinReach(startX:int, startY:int, resource:int, reach:int):Boolean 
{ 
    for (var x:int = startX - reach; x < startX + reach + 1; x++) 
    { 
     for (var y:int = startY - reach; y < startY + reach + 1; y++) 
     { 
      // check if this coordinate exists and if it has the resource we are looking for 
      if (isWithinMap(x, y) && blankMap[y][x] == resource) 
      { 
       // found the resource 
       return true; 
      } 
     } 
    } 

    // nothing found 
    return false; 
} 

// check if a x, y coordinate is within the bounds of the map arrays 
private function isWithinMap(x:int, y:int):Boolean 
{ 
    return x > 0 && y > 0 && x < blankMap[0].length && y < blankMap.length; 
}