如何在Javascript Tic Tac Toe游戏中禁用X&O

时间:2014-12-19 02:34:18

标签: javascript tic-tac-toe

简而言之,我知道这个问题没有意义,让我清楚一点,如果我点击它会改变为X,反之亦然如何解决这个问题? 就像我不知道如何禁用它们以保持放置一样,你们也知道如何用for循环重置游戏而不是手动操作

HTML:

<!DOCTYPE html>
<html>
   <head>
      <title>Tic Tac Toe</title>
      <script text="javascript" src="tic.js"></script>
      <link rel="stylesheet" type="text/css" href="style.css">
   </head>
   <center>
      <body>
         <h1 style="font-family:arial;">Tic-Tac-Toe</h1>
         <table>
            <tr>
               <td id = "case1" onclick="display_input('case1')"></td>
               <td id = "case2" onclick="display_input('case2')"></td>
               <td id = "case3" onclick="display_input('case3')"></td>
            </tr>
            <tr>
               <td id = "case4" onclick="display_input('case4')"></td>
               <td id = "case5" onclick="display_input('case5')"></td>
               <td id = "case6" onclick="display_input('case6')"></td>
            </tr>
            <tr>
               <td id = "case7" onclick="display_input('case7')"></td>
               <td id = "case8" onclick="display_input('case8')"></td>
               <td id = "case9" onclick="display_input('case9')"></td>
            </tr>
         </table>
         <footer>
            <p>Copyright&copy; 2014</p>
         </footer>
      </body>
   </center>
</html>

使用Javascript:

var player_one = 1;
function display_input(square){ 

    if ( player_one == 1 ){
        document.getElementById(square).innerHTML = "X";
        player_one = 0;

    } else {
        document.getElementById(square).innerHTML = "O";    
        player_one = 1;
    }
}

function reset() {

    document.getElementById("case1").innerHTML = "";
    document.getElementById("case2").innerHTML = "";
    document.getElementById("case3").innerHTML = "";
    document.getElementById("case4").innerHTML = "";
    document.getElementById("case5").innerHTML = "";
    document.getElementById("case6").innerHTML = "";
    document.getElementById("case7").innerHTML = "";
    document.getElementById("case8").innerHTML = "";
    document.getElementById("case9").innerHTML = "";
}

2 个答案:

答案 0 :(得分:1)

您可以随时检查方形元素是否为空,如果不是,则不要执行任何操作:

function display_input(square) {
    //We get the associated DOM element
    var element = document.getElementById(square);

    //If the element already contains something, then don't change it
    if(element.innerHTML != "") return;

    if(player_one == 1) {
        element.innerHTML = "X";
        player_one = 0;
    } else {
        element.innerHTML = "O";
        player_one = 1;
    }
}

答案 1 :(得分:0)

通过将以下内容添加到display_input(square)来覆盖方块的onclick函数

document.getElementById(square).onclick = function() {return};