Javascript 康威生命游戏-细胞获胜';不要出现在画布上

Javascript 康威生命游戏-细胞获胜';不要出现在画布上,javascript,html,css,Javascript,Html,Css,我试图在网页的画布上编写一个康威生活游戏应用程序。但是,在编写代码之后,我无法使单元格显示在画布元素上。你能看出我做错了什么吗 我的猜测是,这与按钮的功能有关——我编写的功能应该是初始化游戏,但它没有发生 <!DOCTYPE html> <html> <head> <script> var CONWAY = (function() { var my = {};

我试图在网页的画布上编写一个康威生活游戏应用程序。但是,在编写代码之后,我无法使单元格显示在画布元素上。你能看出我做错了什么吗

我的猜测是,这与按钮的功能有关——我编写的功能应该是初始化游戏,但它没有发生

    <!DOCTYPE html>
    <html>
    <head>
    <script>
        var CONWAY = (function() {
            var my = {};
                var Board = function() { //create a game board object
                this.cells = {};  //collection object to hold cell coordinates
                };

                var Cell = function(x, y, alive) { //create a cell object
                    this.x = x; //the x coordinate for the cell
                    this.y = y; //the y coordinate for the cell
                    this.alive = alive;  //state to show if the cell is alive or dead
                };


                Cell.prototype = { //add isAlive method to the cell object
                    isAlive: function() {
                        return this.alive; //return cell's state
                    }
                };

                Board.prototype = {
                    addCell: function(cell) {  //the method to add a cell to the board
                        this.cells[getCellRepresentation(cell.x, cell.y)] = cell;
                    },
                    getCellAt: function(x,y) {  //returns the value of the specified coordinates
                        return this.cells[getCellRepresentation(x,y)];
                    },
                    getAliveNeighbors: function(cell) { //check nearby cells for states according to the rules
                        var x = cell.x;
                        var y = cell.y;
                        var aliveCells = 0;

                        for(var i = -1; i < 2; i++) { //look for live cells in the vicinity
                            for(var j = -1; j < 2; j++) {
                                if(i === 0 && i === j) {
                                    continue;
                                }
                                var currentCell = this.getCellAt(x + i, y + j);
                                if(currentCell && currentCell.isAlive()) {
                                    aliveCells++;
                                }
                            }
                        }
                        return aliveCells; //return the number of live cells
                    },
                    calculateNextState: function(cell) {
                        var tempCell = new Cell(cell.x, cell.y, cell.alive);
                        var livingNeighbors = this.getAliveNeighbors(cell);

                        if(cell.alive) {
                            if(livingNeighbors === 2 || livingNeighbors === 3) {
                                tempCell.alive = true;
                            }
                            else {
                                tempCell.alive = false;
                            }
                        }
                        else {
                            if(livingNeighbors === 3) {
                                tempCell.alive = true;
                            }
                        }
                        return tempCell;
                    },
                    step: function() {
                        var cells = this.cells;
                        var tempBoard = {};

                        for(var c in this.cells) {
                            var cell = this.cells[c];
                            var newCell = this.calculateNextState(cell);
                            tempBoard[c] = newCell;
                        }
                        this.cells = tempBoard;
                    }        
                };

                function getCellPrepresentation (x,y) {
                    return "x" + x + "y" + y;    
                }



        var CONWAY_GLOB_MAX_X = 99;
        var CONWAY_GLOB_MAX_Y = 23;
        var randomInit = function(board) {
            for (var y = 0; y <= CONWAY_GLOB_MAX_Y; y++) {
                for (var x = 0; x <= CONWAY_GLOB_MAX_X; x++) {
                    board.addCell(new Cell(x, y, (Math.random() > 0.8)));
                }
            }
        };
        var draw = function(board, canvas) {
            var output = ' ';
            for(var y = 0; y <= CONWAY_GLOB_MAX_X; y++) {
                for(var x = 0; x <= CONWAY_GLOB_MAX_Y; x++) {
                    var cell = board.getCellAt(x,y);
                    output += cell && cell.isAlive() ? 'o' : ' ';
                }
                output += '\n\
                ';
            }
            canvas.html(output);
        };

        var doConway = function(body) {
            var board = new Board(); //create new board

            randomInit(board); //initialize board with random dead and alive cells

            draw(board, body); //draw the board

            return setInterval(function() { //update every 130 ms
                board.step();
                draw(board, body);
            }, 130);
        };

        my.initConway = function(id, body) {
            clearInterval(id);
            return doConway(body);
        };

        my.resetConway = function(id, body) {
            body.empty();
            clearInterval(id);
        };
                var conwayRandIntervalId = null;
    var conwayBody = getElementbyId('conway');
    var resetGame = function() {
        this.resetConway(conwayRandIntervalId, conwayBody);
    };
    var startGame = function() {
        conwayRandIntervalId = this.initConway(conwayRandIntervalId, conwayBody);
    }
    return my;
    }());


    </script>

    <style type="text/css">
        div.conway {
            overflow: hidden;
            font-family: courier;
            float: left;
            width: 500px; 
            height: 288px;
            background-color: #000;
            font-size: 10px;
            color: #fff;
        }
    </style>
    </head>
    <body>
    <div>
        <button id='startCW' onclick="startGame();">Random Conway's Game of      Life</button> | <button id='resetCW' onclick="resetGame();">Reset</button>
        <div class='conway' id='conway'></div> 
    </div>
    </body>
    </html>

var CONWAY=(函数(){
var my={};
var Board=function(){//创建游戏板对象
this.cells={};//用于保存单元格坐标的集合对象
};
var Cell=函数(x,y,alive){//创建一个Cell对象
this.x=x;//单元格的x坐标
this.y=y;//单元格的y坐标
this.alive=alive;//状态以显示单元格是活的还是死的
};
Cell.prototype={//add isAlive方法到Cell对象
isAlive:function(){
返回this.alive;//返回单元格的状态
}
};
Board.prototype={
addCell:function(cell){//将单元格添加到电路板的方法
this.cells[getCellRepresentation(cell.x,cell.y)]=单元格;
},
函数(x,y){//返回指定坐标的值
返回此.cells[getCellRepresentation(x,y)];
},
getAliveNeighbors:function(cell){//根据规则检查附近的单元格的状态
var x=单元格x;
var y=cell.y;
var-aliveCells=0;
对于(var i=-1;i<2;i++){//在附近寻找活细胞
对于(var j=-1;j<2;j++){
如果(i==0&&i==j){
继续;
}
var currentCell=this.getCellAt(x+i,y+j);
if(currentCell&¤tCell.isAlive()){
aliveCells++;
}
}
}
return aliveCells;//返回活细胞数
},
CalculateNext状态:函数(单元格){
var tempCell=新单元(Cell.x、Cell.y、Cell.alive);
var livingNeighbors=此.getAliveNeighbors(单元格);
如果(活细胞){
如果(LivingNeights==2 | | LivingNeights==3){
tempCell.alive=true;
}
否则{
tempCell.alive=false;
}
}
否则{
如果(生活邻居===3){
tempCell.alive=true;
}
}
返回tempCell;
},
步骤:函数(){
var单元格=此.cells;
var tempBoard={};
for(此.cells中的变量c){
var cell=this.cells[c];
var newCell=this.calculateNext状态(单元格);
tempBoard[c]=newCell;
}
此.cells=临时板;
}        
};
函数getCellPrepresentation(x,y){
返回“x”+x+“y”+y;
}
var CONWAY_GLOB_MAX_X=99;
var CONWAY_GLOB_MAX_Y=23;
var randomInit=功能(板){

对于(var y=0;y我有一点时间,所以我冒昧地修复了这个应用程序

最初的问题是您没有正确地公开函数startName,该按钮无法触发它。我通过在my上设置的
CONWAY
对象将其公开。然后您丢失了
文档的
部分。getElementById
。接下来您尝试调用
getCellRepresentation
,但它应该是
getcellpresentation

下一个问题与在加载dom之前执行脚本有关。有几种方法可以解决这个问题,例如使用jquerys document load函数并将逻辑放在其中,但最简单的方法是将脚本标记作为正文中的最后一个标记。当浏览器在html中迭代时,它将生成加载dom元素,然后执行代码,这允许
document.getElementById
返回正确的元素。在加载dom之前执行此操作将始终返回null

我将您的
canvas.html(output)
更改为
canvas.innerHTML=output
,因为这是对jquery的依赖,而我的机器上没有这种依赖。任何一种方式都可以接受

最后,我清理了您的输出。在您的版本中,由于您正在使用空格和\n之类的操作,输出全部落在一行上。由于我们在html块中,我将输出更改为
's和

。另一种解决方案是使用
元素而不是div,但我没有测试过他的

<!DOCTYPE html>
<html>
<head>

    <style type="text/css">
        div.conway {
            overflow: hidden;
            font-family: courier;
            float: left;
            width: 500px;
            height: 288px;
            background-color: #000;
            font-size: 10px;
            color: #fff;
        }
    </style>
</head>
<body>
    <div>
        <button id='startCW' onclick="CONWAY.startGame();">Random Conway's Game of      Life</button> | <button id='resetCW' onclick="    CONWAY.resetGame();">Reset</button>
        <div class='conway' id='conway'></div>
    </div>

    <script type="text/javascript">
    var CONWAY = (function () {
        var my = {};
        var Board = function () { //create a game board object
            this.cells = {};  //collection object to hold cell coordinates
        };

        var Cell = function (x, y, alive) { //create a cell object
            this.x = x; //the x coordinate for the cell
            this.y = y; //the y coordinate for the cell
            this.alive = alive;  //state to show if the cell is alive or dead
        };


        Cell.prototype = { //add isAlive method to the cell object
            isAlive: function () {
                return this.alive; //return cell's state
            }
        };

        Board.prototype = {
            addCell: function (cell) {  //the method to add a cell to the board
                this.cells[getCellPrepresentation(cell.x, cell.y)] = cell;
            },
            getCellAt: function (x, y) {  //returns the value of the specified coordinates
                return this.cells[getCellPrepresentation(x, y)];
            },
            getAliveNeighbors: function (cell) { //check nearby cells for states according to the rules
                var x = cell.x;
                var y = cell.y;
                var aliveCells = 0;

                for (var i = -1; i < 2; i++) { //look for live cells in the vicinity
                    for (var j = -1; j < 2; j++) {
                        if (i === 0 && i === j) {
                            continue;
                        }
                        var currentCell = this.getCellAt(x + i, y + j);
                        if (currentCell && currentCell.isAlive()) {
                            aliveCells++;
                        }
                    }
                }
                return aliveCells; //return the number of live cells
            },
            calculateNextState: function (cell) {
                var tempCell = new Cell(cell.x, cell.y, cell.alive);
                var livingNeighbors = this.getAliveNeighbors(cell);

                if (cell.alive) {
                    if (livingNeighbors === 2 || livingNeighbors === 3) {
                        tempCell.alive = true;
                    }
                    else {
                        tempCell.alive = false;
                    }
                }
                else {
                    if (livingNeighbors === 3) {
                        tempCell.alive = true;
                    }
                }
                return tempCell;
            },
            step: function () {
                var cells = this.cells;
                var tempBoard = {};

                for (var c in this.cells) {
                    var cell = this.cells[c];
                    var newCell = this.calculateNextState(cell);
                    tempBoard[c] = newCell;
                }
                this.cells = tempBoard;
            }
        };

        function getCellPrepresentation(x, y) {
            return "x" + x + "y" + y;
        }



        var CONWAY_GLOB_MAX_X = 99;
        var CONWAY_GLOB_MAX_Y = 23;
        var randomInit = function (board) {
            for (var y = 0; y <= CONWAY_GLOB_MAX_Y; y++) {
                for (var x = 0; x <= CONWAY_GLOB_MAX_X; x++) {
                    board.addCell(new Cell(x, y, (Math.random() > 0.8)));
                }
            }
        };
        var draw = function (board, canvas) {
            var output = ' ';
            for (var y = 0; y <= CONWAY_GLOB_MAX_X; y++) {
                for (var x = 0; x <= CONWAY_GLOB_MAX_Y; x++) {
                    var cell = board.getCellAt(x, y);
                    output += cell && cell.isAlive() ? 'o' : '&nbsp;';
                }
                output += '<br/>';
            }
            canvas.innerHTML=(output);
        };

        var doConway = function (body) {
            var board = new Board(); //create new board

            randomInit(board); //initialize board with random dead and alive cells

            draw(board, body); //draw the board

            return setInterval(function () { //update every 130 ms
                board.step();
                draw(board, body);
            }, 130);
        };

        my.initConway = function (id, body) {
            clearInterval(id);
            return doConway(body);
        };

        my.resetConway = function (id, body) {
            body.empty();
            clearInterval(id);
        };
        var conwayRandIntervalId = null;
        var conwayBody = document.getElementById('conway');
        my.resetGame = function () {
            this.resetConway(conwayRandIntervalId, conwayBody);
        };
        my.startGame = function () {
            conwayRandIntervalId = this.initConway(conwayRandIntervalId, conwayBody);
        }
        return my;
    }());


    </script>


</body>
</html>
我可能在帮助方面做得有点过头了,如果您只是想了解没有输出的原因,那么很抱歉。如果您有任何问题,请发表评论:-)


康威分区{
溢出:隐藏;
字体系列:信使;
浮动:左;