Bootstrap

js实现在线五子棋小游戏(人机对战)

js五子棋对战小游戏,利用一个小小的算法,可实现人机对战。

话不多说多,先上demo:

五子棋小游戏 - UD在线工具箱icon-default.png?t=O83Ahttps://www.udtool.com/toolbox/wuziqis.html下面是截图:

下面是js代码:

var over = false;
    var me = true; 
    var _nowi = 0, _nowj = 0; 
    var _compi = 0, _compj = 0;
    var _myWin = [], _compWin = []; 
    var backAble = false, returnAble = false;
    var gesize = 19;
    var ci = null;
    var cj = null;

    if($(window).width() < 1000 && $(window).width() > 890){
        gesize = 15;
    }

    if($(window).width() < 700 && $(window).width() >= 500){
        gesize = 15;
    }

    if($(window).width() < 500){
        gesize = 10;
    }

    $('body').on('click','.vidows',function(){
        if($(this).attr('data-type') == 'on'){
            $(this).html('<span>声音:关</span>');
            $(this).attr('data-type','off');
            setCookie('wuziqiisvids','off',864000);
        }else{
            $(this).html('<span>声音:开</span>');
            $(this).attr('data-type','on');
            setCookie('wuziqiisvids','on',864000);
        }
    });

    // ###############################

    var chess = document.getElementById("chess");

    
    chess.width = gesize * 30; 
    chess.height = gesize * 30;
    var context = chess.getContext('2d');
    var contsis = (gesize * 30) - 15;

    context.fillStyle = '#ebcd95';
    context.fillRect(0, 0, chess.width, chess.height);

    context.strokeStyle = '#bd925d';
    context.lineWidth = 1;
    
    for (var i = 0; i < gesize; i++) {
        context.moveTo(15 + i * 30, 15);
        context.lineTo(15 + i * 30, contsis);
        context.stroke();
        context.moveTo(15, 15 + i * 30);
        context.lineTo(contsis, 15 + i * 30);
        context.stroke();
    }

    // ###############################

    var chressBord = [];
    for (var i = 0; i < gesize; i++) {
        chressBord[i] = [];
        for (var j = 0; j < gesize; j++) {
            chressBord[i][j] = 0;
        }
    }

    // ###############################

    var myWin = [];
    var computerWin = [];

    var wins = [];
    for (var i = 0; i < gesize; i++) {
        wins[i] = [];
        for (var j = 0; j < gesize; j++) {
            wins[i][j] = [];
        }
    }
    var is = wins;
    console.log(is);
    var count = 0;
    // 横向算法
    for (var i = 0; i < gesize; i++) {
        for (var j = 0; j < (gesize - 4); j++) {
            for (var k = 0; k < 5; k++) {
                wins[i][j + k][count] = true;
            }
            count++;
        }
    }
    //竖向算法
    for (var i = 0; i < gesize; i++) {
        for (var j = 0; j < (gesize - 4); j++) {
            for (var k = 0; k < 5; k++) {
                wins[j + k][i][count] = true;
            }
            count++;
        }
    }
    for (var i = 0; i < (gesize - 4); i++) {
        for (var j = 0; j < (gesize - 4); j++) {
            for (var k = 0; k < 5; k++) {
                wins[i + k][j + k][count] = true;
            }
            count++;
        }
    }
    for (var i = 0; i < (gesize - 4); i++) {
        for (var j = (gesize - 1); j > 3; j--) {
            for (var k = 0; k < 5; k++) {
                wins[i + k][j - k][count] = true;
            }
            count++;
        }
    }


    for (var i = 0; i < count; i++) {
        myWin[i] = 0;
        _myWin[i] = 0;
        computerWin[i] = 0;
        _compWin[i] = 0;
    }
    

    var backbtn = document.getElementById("goback");
    var returnbtn = document.getElementById("return");

    chess.onclick = function (e) {
        if(over) {return;}
        if(!me) {return;}
        backbtn.className = backbtn.className.replace(new RegExp("(\\s|^)unable(\\s|$)"), " ");
        var x = e.offsetX;
        var y = e.offsetY;
        var i = Math.floor(x / 30);
        var j = Math.floor(y / 30);
        _nowi = i;
        _nowj = j;
        if (chressBord[i][j] == 0) {
            oneStep(i, j, me);
            chressBord[i][j] = 1; 
            for (var k = 0; k < count; k++) { 
                if (wins[i][j][k]) {
                    myWin[k]++;
                    _compWin[k] = computerWin[k];
                    computerWin[k] = 6;
                    if (myWin[k] == 5) {
                        layer.alert('ଘ(੭ˊᵕˋ)੭ 恭喜,你赢了!',{ 
                            btn: ['重新开启', '关闭'],
                            btn1: function(){
                                window.location.reload()
                            },
                            btn2: function(){
                                layer.closeAll();
                            }
                        });
                        over = true;
                    }
                }
            }
            if (!over) {
                me = !me;
                computerAI();
            }
        }
    }

    backbtn.onclick = function (e) {
        if (!backAble) { return; }
        over = false;
        me = true;
        layer.msg('悔棋中...',{time:500});
        returnbtn.className = returnbtn.className.replace(new RegExp("(\\s|^)unable(\\s|$)"), " ");
        chressBord[_nowi][_nowj] = 0; 
        minusStep(_nowi, _nowj); 
        for (var k = 0; k < count; k++) { 
            if (wins[_nowi][_nowj][k]) {
                myWin[k]--;
                computerWin[k] = _compWin[k];
            }
        }
        chressBord[_compi][_compj] = 0; 
        minusStep(_compi, _compj); 
        for (var k = 0; k < count; k++) { 
            if (wins[_compi][_compj][k]) {
                computerWin[k]--;
                myWin[k] = _myWin[i];
            }
        }
        returnAble = true;
        backAble = false;
    }

    returnbtn.onclick = function (e) {
        if (!returnAble) { return; }
        layer.msg('撤销悔棋中...',{time:500});
        chressBord[_nowi][_nowj] = 1; 
        oneStep(_nowi, _nowj, me);
        for (var k = 0; k < count; k++) {
            if (wins[_nowi][_nowj][k]) {
                myWin[k]++;
                _compWin[k] = computerWin[k];
                computerWin[k] = 6;
            }
            if (myWin[k] == 5) {
                layer.alert('ଘ(੭ˊᵕˋ)੭ 恭喜,你赢了!',{ 
                    btn: ['重新开启', '关闭'],
                    btn1: function(){
                        window.location.reload()
                    },
                    btn2: function(){
                        layer.closeAll();
                    }
                });
                over = true;
            }
        }
        chressBord[_compi][_compj] = 2;   
        oneStep(_compi, _compj, false);
        for (var k = 0; k < count; k++) { 
            if (wins[_compi][_compj][k]) {
                computerWin[k]++;
                _myWin[k] = myWin[k];
                myWin[k] = 6;
            }
            if (computerWin[k] == 5) {
                layer.alert('╰( 0ω0)ノ 你输了,继续加油哦!',{ 
                    btn: ['重新开启', '关闭'],
                    btn1: function(){
                        window.location.reload()
                    },
                    btn2: function(){
                        layer.closeAll();
                    }
                });
                over = true;
            }
        }
        returnbtn.className += ' ' + 'unable';
        returnAble = false;
        backAble = true;
    }
 
    var computerAI = function () {
        var myScore = [];
        var computerScore = [];
        var max = 0;
        var u = 0, v = 0;
        for (var i = 0; i < gesize; i++) {
            myScore[i] = [];
            computerScore[i] = [];
            for (var j = 0; j < gesize; j++) {
                myScore[i][j] = 0;
                computerScore[i][j] = 0;
            }
        }
        for (var i = 0; i < gesize; i++) {
            for (var j = 0; j < gesize; j++) {
                if (chressBord[i][j] == 0) {
                    for (var k = 0; k < count; k++) {
                        if (wins[i][j][k]) {
                            if (myWin[k] == 1) {
                                myScore[i][j] += 200;
                            } else if (myWin[k] == 2) {
                                myScore[i][j] += 400;
                            } else if (myWin[k] == 3) {
                                myScore[i][j] += 2000;
                            } else if (myWin[k] == 4) {
                                myScore[i][j] += 10000;
                            }

                            if (computerWin[k] == 1) {
                                computerScore[i][j] += 220;
                            } else if (computerWin[k] == 2) {
                                computerScore[i][j] += 420;
                            } else if (computerWin[k] == 3) {
                                computerScore[i][j] += 2100;
                            } else if (computerWin[k] == 4) {
                                computerScore[i][j] += 20000;
                            }
                        }
                    }

                    if (myScore[i][j] > max) {
                        max = myScore[i][j];
                        u = i;
                        v = j;
                    } else if (myScore[i][j] == max) {
                        if (computerScore[i][j] > computerScore[u][v]) {
                            u = i;
                            v = j;
                        }
                    }

                    if (computerScore[i][j] > max) {
                        max = computerScore[i][j];
                        u = i;
                        v = j;
                    } else if (computerScore[i][j] == max) {
                        if (myScore[i][j] > myScore[u][v]) {
                            u = i;
                            v = j;
                        }
                    }

                }
            }
        }
        _compi = u;
        _compj = v;
        oneStep(u, v, false);
        chressBord[u][v] = 2; 
        for (var k = 0; k < count; k++) {
            if (wins[u][v][k]) {
                computerWin[k]++;
                _myWin[k] = myWin[k];
                myWin[k] = 6;
                if (computerWin[k] == 5) {
                    layer.alert('╰( 0ω0)ノ 你输了,继续加油哦!',{ 
                        btn: ['重新开启', '关闭'],
                        btn1: function(){
                            window.location.reload()
                        },
                        btn2: function(){
                            layer.closeAll();
                        }
                    });
                    over = true;
                }
            }
        }
        if (!over) {
            me = !me;
        }
        backAble = true;
        returnAble = false;
        var hasClass = new RegExp('unable').test(' ' + returnbtn.className + ' ');
        if (!hasClass) {
            returnbtn.className += ' ' + 'unable';
        }
    }

    var oneStep = function (i, j, me) {
        context.beginPath();
        context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
        context.closePath();
        var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
        if (me) {
            gradient.addColorStop(0, '#000000');
            gradient.addColorStop(1, '#636766');
            if($('.vidows').attr('data-type') == 'on'){
                var chessSound = document.getElementById('chessSound');
                chessSound.play();
            }
            context.fillStyle = gradient;
            context.fill();
        } else {

            gradient.addColorStop(0, '#d1d1d1');
            gradient.addColorStop(1, '#f9f9f9');
            context.fillStyle = gradient;
            context.fill();

            var tempCanvas = document.createElement('canvas');
            tempCanvas.width = 20;
            tempCanvas.height = 20;
            var tempCtx = tempCanvas.getContext('2d');
            var gradientdian = tempCtx.createRadialGradient(10, 10, 0, 10, 10, 10);
            gradientdian.addColorStop(0, 'red'); 
            gradientdian.addColorStop(1, 'rgba(255, 255, 255, 0)');
            tempCtx.fillStyle = gradientdian;
            tempCtx.beginPath();
            tempCtx.arc(10, 10, 10, 0, Math.PI * 2, true); // 半径设置为10
            tempCtx.fill();
            context.drawImage(tempCanvas, 15 + i * 30 - 10, 15 + j * 30 - 10);
            if(ci != null){
                clearAnnotation(ci,cj);
            }
            ci = i;
            cj = j;
        }
    }

    var clearAnnotation = function (i, j) {
        minusStep(i,j);
        context.beginPath();
        context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
        context.closePath();
        var gradientss = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
        gradientss.addColorStop(0, '#d1d1d1');
        gradientss.addColorStop(1, '#f9f9f9');
        context.fillStyle = gradientss;
        context.fill();
    }

    var minusStep = function (i, j) {
        context.clearRect((i) * 30, (j) * 30, 30, 30)
        context.fillStyle = '#ebcd95';
        context.fillRect((i) * 30, (j) * 30, 30, 30);
        context.beginPath();
        context.moveTo(15 + i * 30, j * 30);
        context.lineTo(15 + i * 30, j * 30 + 30);
        context.moveTo(i * 30, j * 30 + 15);
        context.lineTo((i + 1) * 30, j * 30 + 15);
        context.stroke();
    } 

;