2016-12-14 263 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声明是错误的。我在代码片段中添加了一些评论,以指导您完成这些更改。 让我知道如果有什么东西仍然是错的,希望这有助于。