2016-12-14 189 views
0

所以這裏是我想要做的:javascript循環完成後循環打印

兩個對象有hp和power變量。我想在他們之間進行一場戰鬥。邏輯是做一個這樣做的循環:object1HP-object2Power,Object2HP - Object2Power。當其中一個對象的HP爲0或更低時 - 打印誰勝出。

這是我到目前爲止有:

this.battle = function(other) { 
 
    \t do { 
 
      this.hp - other.power; 
 
      other.hp - this.power; 
 
     } 
 
    \t while (this.hp <=0 || other.hp <=0); 
 
     
 
     if(this.hp <=0) { 
 
      console.log(this.name + " won!"); 
 
     } else { 
 
      console.log(other.name + " won!"); 
 
     } 
 
    }

我知道這可能是一個爛攤子。謝謝!

+1

您需要將您的循環更改爲(&&)和> 0,因此它會一直持續到一個低於或等於零 – Pete

回答

0

我不確定你的問題是什麼。代碼段是否工作? 一個微小的細節是彈簧我的眼睛,你可能想要寫

this.hp -= other.power; 
other.hp -= this.power; 

你缺少了「=」,你會得到一個無限循環,因爲變量留不變。

0

這應該是工作代碼片段:

this.battle = function(other) { 
 
    \t do { 
 
      this.hp = this.hp - other.power; //Need to set this.hp equal to it, or nothing is changing 
 
      other.hp = other.hp - this.power; 
 
     } 
 
    \t while (this.hp >=0 && other.hp >=0); //You want to keep running the loop while BOTH players have HP above 0 
 
     
 
     if(this.hp <=0) { //If this has less than zero HP, then the other person won, so you need to inverse it 
 
      console.log(other.name + " won!"); 
 
     } else { 
 
      console.log(this.name + " won!"); 
 
     } 
 
    }

你有第一個問題是,你沒有設置你的變量,你改變了他們之後。只有this.hp - other.power不會將值保存到任何變量中。所以每個循環後this.hp保持不變。爲了解決這個問題,只需通過說this.hp = this.hp - other.power將新值設置爲this.hp

第二個問題是您的while循環的條件不正確。說this.hp <= 0 || other.hp <= 0是說「如果任一玩家的HP小於零,繼續運行」在哪裏你要找的是「如果兩個玩家的HP大於零,繼續運行」

最後,你的邏輯在最後if聲明是錯誤的。我在代碼片段中添加了一些評論,以指導您完成這些更改。 讓我知道如果有什麼東西仍然是錯的,希望這有助於。