任何人都可以告诉我为什么这个Jquery代码没有响应吗?

时间:2012-03-29 22:49:26

标签: javascript jquery

我正在尝试做简单的X O游戏,它似乎工作得很好但是当我到达3“Os” 函数call(),它不会让你在if语句中松动 ,它确实给你赢了,我达到3“Xs”。

<script type="text/javascript" src="jquery.js" ></script>
<script type="text/javascript" >



    function call() {
        var x = Math.floor((Math.random() * 9) + 1);
        if ($('#td' + x).text() === "x" || $('#td' + x).text() === "o") {
            call();
        }

        else if (check() === true) {
            $('div').text("You win ");
            return false;
        }

        else if (checkLoose() === true) {
        $('p').text("You Loose ");
            return false;
        }

        else
            $('#td' + x).text("o");
        }



    function win(as, bs, cc) {
        return ($('#td'+as).text() === "x" && $('#td'+bs).text() === "x" && $('#td'+cc).text() === "x") ;

    }

    function check(){

        if (win(1, 2, 3) || win(1, 4, 7) || win(4, 5, 6) || win(7, 8, 9) || win(2, 5, 8) || win(3, 6, 9) || win(1, 5, 9) || win(3, 5, 7) === true) 
              return true;
 }

 function checkLoose() {

     if (lose(1, 2, 3) || lose(1, 4, 7) || lose(4, 5, 6) || lose(7, 8, 9) || lose(2, 5, 8) || lose(3, 6, 9) || lose(1, 5, 9) || lose(3, 5, 7) === true) {

         return true;
     } 
 }




    function lose(as, bs, cc) {
        return ($('#td' + as).text() === "o" && $('#td' + bs).text() === "o" && $('#td' + cc).text() === "o");

    }

    function dsd(sad) {

        if ($('#td' + sad).text() === "x" || $('#td' + sad).text() === "o")
            return false;

        else if (check() === true)
            return false;

        else if (checkLoose() === true) {

            return false;
        }
        else {
            $("#td" + sad).text("x");
            call();
        }       
        }

        $(document).ready(function(){
        $("td").hover(function () {
            $(this).css("background-color", "yellow");
        }, function () {
            $(this).css("background-color", "white");
        });
    });

</script>

</head>
<body>




<center>
<h1 >"        X ,O Game    "</h1><br />
<div></div>
<p></p>
<table>
    <tr>
       <td id="td1"  onclick="dsd(1);" ></td>
       <td id="td2" onclick="dsd(2);"></td>
       <td id="td3" onclick="dsd(3);"></td>
    </tr>

    <tr>
       <td id="td4" onclick="dsd(4);"></td>
       <td id="td5" onclick="dsd(5);"></td>
       <td id="td6" onclick="dsd(6);"></td>
    </tr>

    <tr>
       <td id="td7" onclick="dsd(7);"></td>
       <td id="td8" onclick="dsd(8);"></td>
       <td id="td9" onclick="dsd(9);"</td>
    </tr>
</table>
</center>

2 个答案:

答案 0 :(得分:1)

您的支票(和checkLoose)仅在点击期间被调用。 您需要在call()函数中添加o的行之后检查胜负。

$('#td' + x).text("o");
/* add calls to check() and checkLoose() here */

答案 1 :(得分:0)

在函数调用中,在向单元格添加“o”字母之前检查赢家/输家(这会导致checkLoose不返回true)。如果你之前添加它,checkLoose将返回true(并且游戏将正确更新)

然而,有一个副作用是将它向上移动:如果人类获胜,计算机仍将添加“o”(但是,游戏仍会说“你赢了”) - 你可以在各种方式。我会让你想出那个:)

相关问题