简体   繁体   English

即使不满足条件,while循环的结果仍然会发生

[英]Result of a while loop still happens even when the condition isn't met

I'm practising writing Javascript by making a Roguelike dungeon game but there is a problem when I want to create monsters. 我正在练习通过制作类似于Rogue的地下城游戏来编写Javascript,但是当我要创建怪物时会遇到问题。 I have written a while loop such as: 我写了一个while循环,例如:

this.getRandomCoordinatesInRoom = function(roomNumber) {
var validLocationFound = false;

while (!validLocationFound){
  // Generate co-ords in room first
  x = Math.floor(Math.random() * (this.roomList[roomNumber].width) + (this.roomList[roomNumber].posX));
  y = Math.floor(Math.random() * (this.roomList[roomNumber].height) + (this.roomList[roomNumber].posY));

  // Find location of (x,y) in Dungeon Array

  //alert(arrayLocation);
  var tmpX = ((this.roomList[roomNumber]).posX + x);
  var tmpY = ((this.roomList[roomNumber]).posY + y);
  var arrayLocation = ((tmpY * 80) + tmpX);
  //var arrayLocation = ((this.roomList[roomNumber].posX + x) + (80 * (this.roomList[roomNumber].posY + y)));
  if (this.dungeonArray[(tmpY + tmpX)] === "floor") {
    validLocationFound = true;
  };

  if ((x<this.roomList[roomNumber].posX) || (x>(this.roomList[roomNumber].posX + this.roomList[roomNumber].width))){
    alert("x out of bounds");
  };

  if ((y<this.roomList[roomNumber].posY) || (y>(this.roomList[roomNumber].posY + this.roomList[roomNumber].height))){
    alert("y out of bounds");
  };
  writeToScreen("Room upper left corner = " + (this.roomList[roomNumber].posX).toString() + "," + (this.roomList[roomNumber].posY).toString(),10);
  return [x,y];

  if (!(getTileAt(arrayLocation) === "floor")){
    alert("It messed up");
  }
};

The code randomly generates an x,y coordinate and converts it to a single number (My dungeon array is one dimensional, 0-79 across and then 80 is a new row). 该代码随机生成一个x,y坐标并将其转换为一个数字(我的地牢数组是一维的,跨度为0-79,然后是新行80)。 however, even when the code generates a coordinate that isn't valid (!= "floor"), it still finishes the function as though it returned true. 但是,即使代码生成的坐标无效(!=“ floor”),它仍会完成函数,就好像返回了true一样。 Why is this? 为什么是这样?

Your function returns [x,y] from inside the while loop. 您的函数从while循环内部返回[x,y] Declare the variables outside of the loop and then return the value from outside the loop. 在循环外声明变量,然后从循环外返回值。 Or else, return is when validLocationFound is true. 否则,当validLocationFound为true时返回。

var x, y ;
while(...) {
    ...
}
return [x, y];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM