康威生命游戏 - 细胞不会出现在画布上

时间:2014-07-15 22:57:37

标签: javascript html css

我正在尝试在网页上的画布中编写Conway Game of Life应用程序。但是在编写代码之后,我无法让单元格出现在canvas元素上。你能说出我做错了吗?

我的猜测是与按钮的功能有关 - 我写的功能应该初始化游戏,但它不会发生。

    <!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>

1 个答案:

答案 0 :(得分:1)

我有一点时间,所以我冒昧地修复了这个应用程序。

最初的问题是你没有正确暴露函数startGame,按钮无法触发它。我通过你的CONWAY对象将它暴露在我的身上。然后你错过了document的{​​{1}}部分。接下来,您尝试拨打document.getElementById,但它应该是getCellRepresentation

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

我将您的document.getElementById更改为canvas.html(output),因为这是我在我的计算机上没有依赖的jquery。无论哪种方式都可以接受。

最后我清理了你的输出。在你的版本中,输出全部落在一行上,因为你正在做诸如使用空格和\ n之类的东西。由于我们在一个html块中,我将输出更改为canvas.innerHTML=output&nbsp;。另一个解决方案是使用<br />元素而不是div,但我没有测试过。

我可能在帮助下走得太远了,很抱歉,如果你只是在寻找没有输出的原因。如果您有任何疑问,请发表评论: - )

<pre>