gpt4 book ai didi

Javascript 未定义函数错误

转载 作者:行者123 更新时间:2023-12-02 14:58:20 25 4
gpt4 key购买 nike

我正在用 JavaScript 构建 Conway 的生命游戏。之前的问题已得到解决。...................................................... ......................现在它说:无法读取“for(var i =0; i< this.checkneighbours.length; i++)”中未定义的属性“length”。但我在顶部将 checkneighbours 定义为数组。你知道问题出在哪里吗?

//object constructor
function cell(){
this.alive = Math.random() > 0.7;
this.neighbours = 0; //number of live neighbours
this.checkneighbours = [[-1,-1],[-1,0],[0,-1],[-1,1],[1,-1],[1,0],[0,1],[1,1]];
}


function GoL(size){
this.size = size;
this.grid = this.makeGrid(size);
};

GoL.prototype.makeGrid = function(size){
var grid = [];
for(var i=0; i<size; i++){
var row=[];
for(var j =0; j<size; j++){
row.push(new cell());
}
grid.push(row);
}
return grid;
};

GoL.prototype.drawGrid = function(){
for(var i=0;i<this.size;i++){
var row =this.grid[i];
var rowCell="";
for(var j=0;j<this.size;j++){
var cell = row[j];
if(cell.alive){
rowCell += "X|";
}else{
rowCell += " |";
}
}
console.log(rowCell);
}
};

GoL.prototype.underpopulation = function(ro,col){
var cell = this.grid[ro][col];
if(cell.neighbours <2){
return true;
}else{
return false;
}
};
GoL.prototype.overpopulation = function(ro,col){
var cell = this.grid[ro][col];
if(cell.neighbours >3){
return true;
}else{
return false;
}
};

GoL.prototype.backtolife = function(ro,col){
var cell = this.grid[ro][col];
if(cell.neighbours ===3 && !cell.alive){
return true;
}else{
return false;
}
};

GoL.prototype.update = function(ro,col){
var cell = this.grid[ro][col];
cell.num_of_neighbours = 0;
for(var i =0; i<this.checkneighbours.length; i++){
var checkneighbour = this.checkneighbours[i];
var neighbour1 = direction[0];
var neighbour2 = direction[1];
if(neighbour1>=0 && neighbour1 < this.size && neighbour2 >=0 && neighbour2 < this.size){
var currentneighbour = this.grid[ro + neighbour1][col+neighbour2];
if(currentneighbour.alive){
cell.num_of_neighbours++;
}
}
}
};

GoL.prototype.updateAll = function(){
for(var i=0; i<this.size;i++){
for(var j=0; j<this.size;j++){
this.update(i,j);
}
}
}

GoL.prototype.cellstatus = function(ro,col){
var cell = this.grid[ro][col];
if(this.underpopulation(ro,col) || this.overpopulation(ro,col)){
cell.alive = false;
}else if(this.backtolife(ro,col)){
cell.alive = true;
}
};

GoL.prototype.allcellstatus = function(ro,col){
for(var i=0; i<this.size;i++){
for(var j=0; j<this.size;j++){
this.cellstatus(i,j);
}
}
};


var gameoflife = new GoL(40);

var interval = setInterval(function(){
GoL.drawGrid();
GoL.updateAll();
GoL.allcellstatus();
},200);

最佳答案

我认为你的意思是

var gameoflife = new GoL(40);
var interval = setInterval(function(){
gameoflife.drawGrid();
gameoflife.updateAll();
gameoflife.allcellstatus();
},200);

关于Javascript 未定义函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35610916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com