2016-09-17 67 views
0

我正在做一个战舰游戏。我想要放置3个长度为3个瓷砖的小船,而不要重叠。我已经写以下代码:问题与调用方法

var boatGrid = { 

    placeBoat : function() { 
     for (boatNum = 1; boatNum < 4; boatNum++) { 
      console.log("boat placed now"); 
      this.selectPos(); 
      document.getElementById("boattest").innerHTML = boatPos; 
      if (document.getElementById(boatPos).hasBoat == 1) { 
       this.placeBoat(); 
       document.getElementById("boattest").innerHTML = "failed"; 
      } 
      else { 
       this.buildBoat();   
      } 
     } 
    }, 

    selectPos : function() { 
      xPos = Math.floor(Math.random() * 8 + 1); 
      yPos = Math.floor(Math.random() * 10 + 1); 
      boatPos = "cell_" + xPos + "_" + yPos; 
    }, 

    buildBoat : function() { 
     for (boatLen = 1; boatLen < 4; boatLen++) { 
      boatPos = "cell_" + xPos + "_" + yPos; 
      xPos = xPos + 1; 
      document.getElementById(boatPos).hasBoat = 1; 
      document.getElementById(boatPos).style.backgroundColor = "brown"; 
      console.log("placed one tile"); 
     } 

    }, 

    clearTable : function() { 
     for (y = 1; y < 11; y++) { 
      for (x = 1; x < 11; x++) { 
       boatPos = "cell_" + x + "_" + y; 
       document.getElementById(boatPos).hasBoat = 0; 
       document.getElementById(boatPos).boatHere = 0; 
       document.getElementById(boatPos).style.backgroundColor = "#34B0D9" 
       document.getElementById(boatPos).innerHTML = "<pre>  </pre>"; 
       boatGrid.hasChecked = 0; 
      } 
     } 
    }, 
} 

当选择两次(可变boatPos存储坐标)的坐标,该函数placeBoat()应该记得本身。但是,实际发生的情况是buildBoat()函数被调用两次。你们中的任何人都能看到问题吗?我目前认为使用placeBoat()函数不得不从内部回想自己是一个问题,但我不知道如何解决这个问题。所有帮助赞赏。

回答

0

我将存储boatPos作为内部boatGrid全局变量,像:

var boatGrid = { 
    boatPos: 0, 

    placeBoat : function() { 
     for (boatNum = 1; boatNum < 4; boatNum++) { 
      //same code as before 
      if (this.boatPos == 1) { 
       this.placeBoat(); 
      // same code as before 
     } 
    }, 

    buildBoat : function() { 
     for (boatLen = 1; boatLen < 4; boatLen++) { 
      //same code as before 
      this.boatPos = 1; 
      // same code as before 
     } 
    }, 
} 

如果你需要存储更多的属性在boatPos(因为它似乎),使用对象:

boatPos = { 
    hasBoat: 0, 
}, 

然后,在功能:

if (this.boatPos.hasBoat == 1) 

this.boatPos.hasBoat = 1; 
+1

我不认为在这样的对象定义中声明一个变量是合法的。你的意思是让它成为一个财产吗? – Andbdrew

+0

@Andbdrew是的,我有点快。我编辑了答案以匹配代码。 – falkodev

+0

boatPos被定义在对象之外,无论如何,为什么会让它运行两次buildBoat()函数? –