html记录之康威生命游戏(二)

html记录之康威生命游戏(二)

尝试:将setInterval定时循环的方式改完setInterval+普通循环
结果:成功。

html记录之康威生命游戏(一)
html记录之康威生命游戏(三)

生命游戏是康威发明的,一种基于元胞自动机下的一种特殊规则,这个规则很简单,但是很强大,这个规则仿佛赋予了静态的东西有了生命一样在运动,有生存和死亡。

生命游戏规则:
每个细胞的生或者死均由周围的8个细胞决定,如果周围生命过多,将会因为资源不足而死亡,如果周围生命过少将会因为孤独而死亡,只有周围生命刚刚好才能处于生的状态。
规则一:如果周围细胞数大于3或者小于2,将会因为资源不足或者孤独而死。
规则二:如果周围刚好有3个细胞,如果原来是生则不变,如果是死将变为生,即为生命的诞生。
规则三:如果周围刚好有2个细胞,那么无论是生是死都不发生任何改变。

实现代码如下:

<html>
    <head>
        <meta charset="utf-8">
        <meta name="author" content="hwq">
        <title>康威生命游戏</title>
        <style>
            *{
                box-sizing: border-box;
            }
            #content{
                width: 1842px;
                height: 1682px;
                border: 1px solid #606060;
                margin: 0 auto;
                position: relative;
                background-color: #494949;
                z-index: 100;
            }
            #topOccupied{
                height: 25px;
            }
            #header{
                width: 100%;
                text-align: center;
                position: fixed;
                z-index: 200;
            }
            #generationInput{
                text-align: center;
            }
            .cell{
                border: 1px solid #606060;
                position: absolute;
            }
        </style>
    </head>
    <body>
        <div id="header">
            <button id="zanting">开始生命游戏</button>
            <button id="restart">初始化</button>
            <button id="tochange">暂停/继续</button>
            <input id="generationInput" type="text" value="第0代" disabled="disabled">
        </div>
        <div id="topOccupied"></div>
        <div id="content">
            
        </div>
        <script>
            //尝试:将setInterval定时循环的方式改完setInterval+普通循环
            console.log("初始化生命游戏");
            let zanting = document.getElementById('zanting');//获取开始按钮dom元素
            let restart = document.getElementById('restart');//获取重新开始dom元素
            let tochange = document.getElementById('tochange');//获取暂停继续dom元素
            let generationInput = document.getElementById('generationInput');//获取暂停继续dom元素
            let content = document.getElementById("content");//获取容器dom元素

            let sizeLeft = 230;//横向格子数
            let sizeTop = 210;//纵向格子数
            let width = content.clientWidth;//容器宽度
            let height = content.clientHeight;//容器高度
            let sizeLeftCal = sizeLeft - 1;//横向坐标上限
            let sizeTopCal = sizeTop - 1;//纵向坐标上限
            let cellWidth = width/sizeLeft;//单个格子宽度
            let cellHeight = height/sizeTop;//单个格子高度
            let lifeCount = 0;//存活计数
            let clickStatus = true;//是否可点击,开始之后不再点亮格子
            let lifeReal = {};//保存所有存活格子,存活放入,死亡移除
            let lifeRealJudge = {};//保存所有需要判断周围生存数量的格子
            let lifeDead = {};//保存所有需要死亡的格子,死亡放入
            let generation = 1;//演化代数
            let cellColor = "#FFF";//格子颜色
            // let loopNumber = 0;//循环次数
            let runStatus = true;//运行状态 true正常运行,false暂停运行
            console.log("width:" + width);
            console.log("height:" + height);
            console.log("sizeLeft:" + sizeLeft);
            console.log("sizeTop:" + sizeTop);
            console.log("cellWidth:" + cellWidth);
            console.log("cellHeight:" + cellHeight);
            //格子实时信息0死1生
            let cellArray = new Array();
            //格子周围实时数量信息(用来判断下一轮生和死的状态)
            //也可以不保存实时数量,采用周围8个格子的方式判断生和死
            let cellLife = new Array();
            //初始化
            createCells();
            //新建格子
            function createCells(){
                for(let i=0; i<sizeLeft; i++){
                    cellArray[i] = new Array();
                    cellLife[i] = new Array();
                    for(let j=0; j<sizeTop; j++){
                        createCell(i, j);
                        cellArray[i][j] = 0;
                        cellLife[i][j] = 0;
                    }
                }
            }
            //新建格子
            function createCell(i, j){
                let div = document.createElement("div");
                div.id = "cell-" + i + "-" + j;
                div.style.width = cellWidth;
                div.style.height = cellHeight;
                div.style.left = (cellWidth*i) + "px";
                div.style.top = (cellHeight*j) + "px";
                // div.style.fontSize = 5;
                // div.innerHTML = i + "" + j;
                div.setAttribute("class", "cell");
                div.addEventListener("click", colorChange, false);//绑定格子颜色转换事件
                content.appendChild(div);
            }
            //格子颜色转换事件
            function colorChange(){
                if(!clickStatus){
                    return;
                }
                console.log(this.id);
                let arr = this.id.split("-");
                let i = arr[1] * 1;
                let j = arr[2] * 1;
                if(this.style.backgroundColor){
                    this.style.backgroundColor = "";
                    if(cellArray[i][j] == 1){
                        lifeNumber(i, j, -1, cellLife);
                        lifeCount--;
                        delete lifeReal["cell-" + i + "-" + j];
                    }
                    cellArray[i][j] = 0;
                }else{
                    this.style.backgroundColor = cellColor;
                    if(cellArray[i][j] == 0){
                        lifeNumber(i, j, 1, cellLife);
                        lifeCount++;
                        lifeReal["cell-" + i + "-" + j] = 1;
                    }
                    cellArray[i][j] = 1;
                }
            }
            //暂停/继续
            tochange.addEventListener("click", toChange, false);
            function toChange(){
                runStatus = !runStatus;
            }
            //初始化
            restart.addEventListener("click", reStart, false);
            function reStart(){
                if(!(typeof timer === "undefined")){
                    clearInterval(timer);//清空循环控制器
                }
                runStatus = true;
                clickStatus = true;
                generation = 0;
                loopNumber = 0;
                lifeReal = {};
                lifeRealJudge = {};
                for(let i=0; i<sizeLeft; i++){
                    cellArray[i] = new Array();
                    cellLife[i] = new Array();
                    for(let j=0; j<sizeTop; j++){
                        cellArray[i][j] = 0;
                        cellLife[i][j] = 0;
                        document.getElementById("cell-" + i + "-" + j).style.backgroundColor = "";
                    }
                }
            }
            //开始生命游戏
            zanting.addEventListener("click", start, false);
            function start(){
                console.log("开始生命游戏");
                let t1 = new Date().getTime();//计算每轮演变消耗时间
                if(lifeCount == 0){
                    clickStatus = true;
                    console.log("没有存活的生命体,请先激活");
                    return;
                }
                clickStatus = false;//开始生命游戏之后不能点亮格子
                var count = 0;
                let swap = false;
                let cellLifeNew = new Array();
                for(let x=0; x<sizeLeft; x++){
                    cellLifeNew[x] = new Array();
                    for(let y=0; y<sizeTop; y++){
                        cellLifeNew[x][y] = cellLife[x][y];
                    }
                }

                let arr;
                let k;
                let q;
                //获取所有需要判断的格子
                let keys = Object.keys(lifeReal);
                for(let con=0; con<keys.length; con++){
                    arr = keys[con].split("-");
                    k = arr[1] * 1;
                    q = arr[2] * 1;
                    lifeRealJudge["cell-" + k + "-" + q] = 1;
                    lifeRealJudge["cell-" + k + "-" + (q-1)] = 1;
                    lifeRealJudge["cell-" + k + "-" + (q+1)] = 1;
                    lifeRealJudge["cell-" + (k-1) + "-" + q] = 1;
                    lifeRealJudge["cell-" + (k-1) + "-" + (q-1)] = 1;
                    lifeRealJudge["cell-" + (k-1) + "-" + (q+1)] = 1;
                    lifeRealJudge["cell-" + (k+1) + "-" + q] = 1;
                    lifeRealJudge["cell-" + (k+1) + "-" + (q-1)] = 1;
                    lifeRealJudge["cell-" + (k+1) + "-" + (q+1)] = 1;
                }
                let lifeKeys = Object.keys(lifeRealJudge);
                let length = lifeKeys.length;

                let num;
                var timer = setInterval(() => {
                    // console.log("1");
                    // k = Math.floor(count / sizeLeft);
                    // q = Math.floor(count % sizeTop);
                    if(!runStatus){
                        console.log("暂停运行中");
                        return;
                    }
                    // loopNumber++;
                    // console.log("开始第" + loopNumber + "次循环");
                    while(runStatus){
                        if(lifeCount == 0){//没有存活
                            clearInterval(timer);//清空循环控制器
                            clickStatus = true;
                            console.log("没有存活结束,当前第" + generation + "代");
                            generationInput.value = "第" + generation + "代";
                            generation = 0;
                            return;
                        }
                        if(count >= length){
                            // let t2 = new Date().getTime();//计算每轮演变消耗时间
                            // console.log("循环耗时" + (t2-t1) + "毫秒");
                            if(swap == false){
                                clearInterval(timer);//清空循环控制器
                                clickStatus = true;
                                console.log("没有变换结束,当前第" + generation + "代");
                                generationInput.value = "第" + generation + "代";
                                generation = 0;
                                return;
                            }
                            cellLife = cellLifeNew;
                            cellLifeNew = new Array();
                            for(let x=0; x<sizeLeft; x++){
                                cellLifeNew[x] = new Array();
                                for(let y=0; y<sizeTop; y++){
                                    cellLifeNew[x][y] = cellLife[x][y];
                                }
                            }
                            //重新渲染格子
                            let keysDead = Object.keys(lifeDead);
                            for(let con=0; con<keysDead.length; con++){
                                arr = keysDead[con].split("-");
                                k = arr[1] * 1;
                                q = arr[2] * 1;
                                document.getElementById("cell-" + k + "-" + q).style.backgroundColor = "";
                            }
                            lifeDead = {};
                            //获取所有需要判断的格子
                            lifeRealJudge = {};
                            let keys = Object.keys(lifeReal);
                            for(let con=0; con<keys.length; con++){
                                arr = keys[con].split("-");
                                k = arr[1] * 1;
                                q = arr[2] * 1;
                                lifeRealJudge["cell-" + k + "-" + q] = 1;
                                lifeRealJudge["cell-" + k + "-" + (q-1)] = 1;
                                lifeRealJudge["cell-" + k + "-" + (q+1)] = 1;
                                lifeRealJudge["cell-" + (k-1) + "-" + q] = 1;
                                lifeRealJudge["cell-" + (k-1) + "-" + (q-1)] = 1;
                                lifeRealJudge["cell-" + (k-1) + "-" + (q+1)] = 1;
                                lifeRealJudge["cell-" + (k+1) + "-" + q] = 1;
                                lifeRealJudge["cell-" + (k+1) + "-" + (q-1)] = 1;
                                lifeRealJudge["cell-" + (k+1) + "-" + (q+1)] = 1;
                                document.getElementById("cell-" + k + "-" + q).style.backgroundColor = cellColor;
                            }
                            lifeKeys = Object.keys(lifeRealJudge);
                            length = lifeKeys.length;
                            console.log("lifeReal大小为" + keys.length + ",lifeRealJudge大小为" + length);
                            count = 0;
                            swap = false;
                            let t3 = new Date().getTime();//计算每轮演变消耗时间
                            // console.log("重置耗时" + (t3-t2) + "毫秒");
                            console.log("结束一轮,当前第" + generation + "代,总耗时" + (t3-t1) + "毫秒");
                            generationInput.value = "第" + generation + "代";
                            if((t3-t1) > 1500){
                                // debugger;
                                // runStatus = false;
                                // clickStatus = true;
                                // clearInterval(timer);
                                console.log("出现超长时间消耗,请检查");
                            }
                            generation++;
                            t1 = t3;
                            break;
                        }
                        if(count >= lifeKeys.length){
                            clearInterval(timer);
                            clickStatus = true;
                            console.log("出现异常,请检查");
                            return;
                        }
                        arr = lifeKeys[count].split("-");
                        k = arr[1] * 1;
                        q = arr[2] * 1;
                        if(k < 0 || k >= sizeLeft || q < 0 || q >= sizeTop){
                            count++;
                            // console.log("错误的值:k=" + k + ",q=" + q);
                            console.log("错误的kq值");
                            // return;改为while循环之后,需要将此处的return改为结束单次循环,否则每个错误坐标将花费每个循环间隔时间!!!!!
                            continue;
                        }
                        num = cellLife[k][q];
                        // console.log("cell-" + k + "-" + q + "周围存活数量为:" + num);
                        if(num == 3) {
                            if(cellArray[k][q] == 0){
                                lifeNumber(k, q, 1, cellLifeNew);
                                lifeCount++;
                                swap = true;
                                if(k >= 0 && k < sizeLeft && q >=0 && q < sizeTop){
                                    lifeReal["cell-" + k + "-" + q] = 1;
                                }
                                cellArray[k][q] = 1;
                            }
                        }else if(num > 3 || num < 2){
                            if(cellArray[k][q] == 1){
                                lifeNumber(k, q, -1, cellLifeNew);
                                lifeCount--;
                                swap = true;
                                delete lifeReal["cell-" + k + "-" + q];
                                lifeDead["cell-" + k + "-" + q] = 1;
                                cellArray[k][q] = 0;
                            }
                        }
                        count++;
                    }
                }, 500);
            }
            //生存数量计算
            function lifeNumber(i, j, inc, cellLifeArray){
                i = i * 1;
                j = j * 1;
                // console.log("cell-" + i + "-" + j + "生存数量计算,inc:" + inc);
                if(i !=0 && j != 0 && i != sizeLeftCal && j != sizeTopCal){//如果不为边缘格子,这个判断范围最大,只判断一次的期望值高
                    cellLifeArray[i-1][j] = cellLifeArray[i-1][j] * 1 + inc;//左
                    cellLifeArray[i-1][j-1] = cellLifeArray[i-1][j-1] * 1 + inc;//左上
                    cellLifeArray[i-1][j+1] = cellLifeArray[i-1][j+1] * 1 + inc;//左下
                    cellLifeArray[i][j-1] = cellLifeArray[i][j-1] * 1 + inc;//上
                    cellLifeArray[i][j+1] = cellLifeArray[i][j+1] * 1 + inc;//下
                    cellLifeArray[i+1][j] = cellLifeArray[i+1][j] * 1 + inc;//右
                    cellLifeArray[i+1][j-1] = cellLifeArray[i+1][j-1] * 1 + inc;//右上
                    cellLifeArray[i+1][j+1] = cellLifeArray[i+1][j+1] * 1 + inc;//右下
                }else if(i == 0 && j != 0 && j != sizeTopCal){//如果为左边一片,只有上、右上、右、右下、下
                    console.log("进入左边一片判断");
                    cellLifeArray[i][j-1] = cellLifeArray[i][j-1] * 1 + inc;//上
                    cellLifeArray[i][j+1] = cellLifeArray[i][j+1] * 1 + inc;//下
                    cellLifeArray[i+1][j] = cellLifeArray[i+1][j] * 1 + inc;//右
                    cellLifeArray[i+1][j-1] = cellLifeArray[i+1][j-1] * 1 + inc;//右上
                    cellLifeArray[i+1][j+1] = cellLifeArray[i+1][j+1] * 1 + inc;//右下
                }else if(j == 0 && i != 0 && i != sizeLeftCal){//如果为上边一片,只有左、左下、下、右下、右
                    console.log("进入左边一片判断");
                    cellLifeArray[i-1][j] = cellLifeArray[i-1][j] * 1 + inc;//左
                    cellLifeArray[i-1][j+1] = cellLifeArray[i-1][j+1] * 1 + inc;//左下
                    cellLifeArray[i][j+1] = cellLifeArray[i][j+1] * 1 + inc;//下
                    cellLifeArray[i+1][j] = cellLifeArray[i+1][j] * 1 + inc;//右
                    cellLifeArray[i+1][j+1] = cellLifeArray[i+1][j+1] * 1 + inc;//右下
                }else if(i == sizeLeftCal && j != 0 && j != sizeTopCal){//如果为右边一片,只有上、左上、左、左下、下
                    console.log("进入右边一片判断");
                    cellLifeArray[i-1][j] = cellLifeArray[i-1][j] * 1 + inc;//左
                    cellLifeArray[i-1][j-1] = cellLifeArray[i-1][j-1] * 1 + inc;//左上
                    cellLifeArray[i-1][j+1] = cellLifeArray[i-1][j+1] * 1 + inc;//左下
                    cellLifeArray[i][j-1] = cellLifeArray[i][j-1] * 1 + inc;//上
                    cellLifeArray[i][j+1] = cellLifeArray[i][j+1] * 1 + inc;//下
                }else if(j == sizeTopCal && i != 0 && i != sizeLeftCal){//如果为下边一片,只有左、左上、上、右上、右
                    console.log("进入下边一片判断");
                    cellLifeArray[i-1][j] = cellLifeArray[i-1][j] * 1 + inc;//左
                    cellLifeArray[i-1][j-1] = cellLifeArray[i-1][j-1] * 1 + inc;//左上
                    cellLifeArray[i][j-1] = cellLifeArray[i][j-1] * 1 + inc;//上
                    cellLifeArray[i+1][j] = cellLifeArray[i+1][j] * 1 + inc;//右
                    cellLifeArray[i+1][j-1] = cellLifeArray[i+1][j-1] * 1 + inc;//右上
                }else if(i == 0 && j == 0){//如果为左上角,只有右、右下、下
                    console.log("进入左上角判断");
                    cellLifeArray[i+1][j] = cellLifeArray[i+1][j] * 1 + inc;//右
                    cellLifeArray[i+1][j+1] = cellLifeArray[i+1][j+1] * 1 + inc;//右下
                    cellLifeArray[i][j+1] = cellLifeArray[i][j+1] * 1 + inc;//下
                }else if(i == sizeLeftCal && j == 0){//如果为右上角,只有左、左下、下
                    console.log("进入右上角判断");
                    cellLifeArray[i-1][j] = cellLifeArray[i-1][j] * 1 + inc;//左
                    cellLifeArray[i-1][j+1] = cellLifeArray[i-1][j+1] * 1 + inc;//左下
                    cellLifeArray[i][j+1] = cellLifeArray[i][j+1] * 1 + inc;//下
                }else if(i == 0 && j == sizeTopCal){//如果为左下角,只有上、右上、右
                    console.log("进入左下角判断");
                    cellLifeArray[i][j-1] = cellLifeArray[i][j-1] * 1 + inc;//上
                    cellLifeArray[i+1][j-1] = cellLifeArray[i+1][j-1] * 1 + inc;//右上
                    cellLifeArray[i+1][j] = cellLifeArray[i+1][j] * 1 + inc;//右
                }else if(i == sizeLeftCal && j == sizeTopCal){//如果为右下角,只有上、左上、左
                    console.log("进入右下角判断");
                    cellLifeArray[i][j-1] = cellLifeArray[i][j-1] * 1 + inc;//上
                    cellLifeArray[i-1][j-1] = cellLifeArray[i-1][j-1] * 1 + inc;//左上
                    cellLifeArray[i-1][j] = cellLifeArray[i-1][j] * 1 + inc;//左
                }
            }
        </script>
    </body>
</html>

修改了页面风格,并将完全的计时器改为计时器为存活代数,while循环做存活判断。
预览如下:
在这里插入图片描述
格子大小最好自己定,修改容器content大小、横向纵向格子数sizeLeft和sizeTop,自己看起来舒服最重要。
不过div的数量多了就卡,这个好像html就这样了,没什么办法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值