我刚刚编写了Conway's game of Life的这个实现,但我没有得到该程序的预期结果。我已经阅读了所有文档,我认为我的代码是准确的,我无法查看错误。我想知道是否有人愿意阅读我的代码并解释我做错了什么。
这是我的代码:
let canvas = document.getElementById('mainCanv');
let ctx = canvas.getContext('2d');
let tileWidth = 10;
let tileHeight = 10;
let map = createMultiArray(100,100);
let next = createMultiArray(100,100);
let alive = 0;;
console.table(map)
function main(){
for(let i = 0; i < map.length; i++){
for(let j = 0; j < map[i].length; j++){
if(i>0&&i<map.length-1&&j>0&&j<map.length-1){
if(checkCells(map,j,i) > 3 && map[i][j] == 1){
next[i][j] = 0;
}
else if(checkCells(map,j,i) < 2 && map[i][j] == 1){
next[i][j] = 0;
}
else if(checkCells(map,j,i) == 2 || checkCells(map,j,i) == 3){
next[i][j] = 1;
}
else if(checkCells(map,j,i) == 3 && map[i][j] == 0){
next[i][j] = 1;
}
}
}
}
map = next;
drawMap(map);
}
randomPlacement(map);
function createMultiArray(rows,cols){
let arr = [];
for(let i = 0; i < rows; i++){
arr[i] = [];
for(let j = 0; j < cols; j++){
arr[i][j] = 0;
}
}
return arr;
}
function randomPlacement(map){
let i = 0;
for(let i = 0; i < map.length; i++){
for(let j = 0; j < map[i].length; j++){
map[i][j] = Math.floor(Math.random()*2);
}
}
}
function checkCells(map,x,y){
aliveCells = map[x][y+1]+
map[x][y-1]+
map[x+1][y]+
map[x-1][y]+
map[x+1][y+1]+
map[x-1][y-1]+
map[x+1][y-1]+
map[x-1][y+1];
return aliveCells;
}
function drawMap(map){
for(let i = 0; i < map.length; i++){
for(let j = 0; j < map[i].length; j++){
ctx.fillStyle = 'white';
if(map[i][j] == 1){
ctx.fillStyle = 'black'
}
ctx.fillRect(i*tileWidth,j*tileHeight,tileWidth,tileHeight);
ctx.strokeStyle = 'black';
ctx.strokeRect(i*tileWidth,j*tileHeight,tileWidth,tileHeight);
}
}
}
setInterval(main,50)
&#13;
<!DOCTYPE html>
<html>
<head>
<title>Life</title>
</head>
<body>
<center>
<canvas id="mainCanv" width="1000" height="1000" style="background-color:grey"></canvas>
</center>
<script type="text/javascript" src="Life.js"></script>
</body>
</html>
&#13;