2017-04-15 98 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