2017-04-15 60 views
-3

我目前正在我的高中的计算机科学课上,并正在编写一个程序来模拟康威的生命游戏。我正在使用JavaScript的Code Studio“App Lab”中编写程序,这是我们一直在学习的东西。它在您设计的左侧有一个智能手机。程序没有进入for循环

到目前为止,它已经很好用了,但我正在尝试在屏幕上绘制单元格,并且我的程序拒绝进入将绘制单元格(用按钮表示)的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 
+0

如果你在我们的代码中投掷并抱怨,“它不起作用!”你很可能会受到不好的待遇。您应该阅读常见问题解答,了解如何提出正确问题的建议。 –

+0

如果你正在调用cellBoard,它必须进入for循环,你只是没有得到你期望的结果。你看过控制台输出吗?您可以添加一些控制台日志记录来查明事情正在破裂的地方。 – Difster

+0

@Difster它进入函数,然后更改屏幕,但只是跳过for循环,我会添加调试解除控制台日志。 – Jamerack

回答

1

看起来就像你在drawBoard功能循环,您使用this.widththis.height。但是,您从未设置this.widththis.height。在CellBoard类的初始化代码中,您应该设置this.width = width。它可能会跳过for循环,因为this.width未定义,不符合for循环条件。

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

+0

这是问题,非常感谢! – Jamerack