程序不进入for循环

时间:2017-04-15 04:08:08

标签: javascript

我目前正在高中的一个计算机科学课上,正在编写一个程序来模拟康威的生命游戏。我正在使用JavaScript编写Code Studio“App Lab”中的程序,这是我们一直在学习的内容。它左侧有一个智能手机,你可以设计。

到目前为止一切都很好,但是我正在尝试在屏幕上绘制单元格并且我的程序拒绝进入for循环,这将绘制单元格(表示为按钮)。绘制CellBoard的函数称为drawBoard,是CellBoard对象内部的一个方法。

function Cell(x, y, id) {
  //base unit for the program, can be either dead or alive based on Conway's 
  //Game of Life Rules
  this.xPos = x;
  this.yPos = y;
  this.id = "cell" + id;
  this.alive = false;
  this.aliveNextTurn = false;
  this.aliveNeighbors = 0;
  this.age = 0;

 this.swapState = function(){
    if(this.alive){
      this.alive = false;
    }
    else{
      this.alive = true;
    }
 };
}

function CellBoard(width, height){
  //the board of cells, this object will house all the methods for the rule 
  //checking and state setting
  this.board = [];
  var count = 0;
  for(var x = 0; x<width; x++){
    var boardY =[];
    for(var y = 0; y<height; y++){
      boardY.push(new Cell(x,y,count));
      count++;
    }
    this.board.push(boardY);
  }

  this.drawBoard = function(){
    //draws the board of cells on the screen as buttons so that the user can 
    //initially set them
    setScreen("simulationScreen");
    //console.log("screen set");
    //console.log("starting button making");
    for(var i = 0; i<this.width; i++){  //<----the problem is here
      //console.log("starting loop");
      for(var j = 0; j<this.height; j++){
        //console.log("making button");
        button(this.board[i][j].id, "test");
        setPosition(this.board[i][j].id, 20+(280/i), 20+(280/j), 280/i, 280/j);
        setProperty(this.board[i][j].id, "background-color", rgb(0,0,0)); //black background by default
        //console.log(getProperty(this.board[i][j].id, "x"));
      }
    }
    //console.log("done drawing board");
  };
}

var testBoard = new CellBoard(3, 3);
testBoard.drawBoard();

非常感谢任何帮助,谢谢!

以下是有问题的函数的控制台日志:

screen set
starting button making
done drawing board

1 个答案:

答案 0 :(得分:1)

drawBoard函数的for循环中看起来像是this.widththis.height。但是,您从未设置this.widththis.height。在CellBoard类的初始化代码中,您应该设置this.width = width。它可能正在跳过for循环,因为this.width未定义,不满足for循环条件。

同样,您在this功能中使用drawBoard关键字。在这样的函数中,this将引用函数而不是对象。而不是在初始化代码中,您可能希望创建一个变量来保存this。您可以在初始化代码中执行cell_board = this,然后在cell_board.width函数中使用drawBoard