【问题标题】:Javascript and html Tic Tac Toe winnerJavascript 和 html 井字游戏获胜者
【发布时间】:2020-08-13 11:53:46
【问题描述】:

我正在使用 html、css 和 JavaScript 编写井字游戏。我有一个外部 .js 文件中的 JavaScript 被引用到 .html 文件中。在 .js 文件中,我有一个名为 playerMove 的函数,它允许玩家移动并在玩家“x”和“o”之间切换。我要做的是确定获胜者。

这就是我所拥有的:每个方块,当 onclick(this) 时,引用 playerMove(piece)。每次移动完成后,我想运行一个 if 语句来检查获胜者,但不确定参数是否包含对“piece”或 a、b 和 c 的引用。任何建议将不胜感激。

var turn = 0;   
a = document.getElementById("topLeftSquare").innerHTML;
b = document.getElementById("topMiddleSquare").innerHTML;
c = document.getElementById("topRightSquare").innerHTML;

function playerMove(piece) {
var win;
if(piece.innerHTML != 'X' && piece.innerHTML != 'O'){
    if(turn % 2 == 0){
        document.getElementById('playerDisplay').innerHTML= "X Plays " + printEquation(1);
        piece.innerHTML = 'X';
        window.setInterval("X", 10000)
        piece.style.color = "red";
        if(piece.innerHTML == 'X')
            window.alert("X WINS!");
    }
    else {
        document.getElementById('playerDisplay').innerHTML= "O Plays " + printEquation(1);
        piece.innerHTML = 'O';
        piece.style.color = "brown";
        //document.getElementById('playerDisplay').innerHTML = "O Plays";

        //win = winner();
    }

    turn+=1;
}

html代码:

<div id="board">
            <div class="topLeftSquare" onclick="playerMove(this)">

            </div>
            <div class="topMiddleSquare" onclick="playerMove(this)">

            </div>
            <div class="topRightSquare" onclick="playerMove(this)">

            </div>
</div>

【问题讨论】:

  • 你能提供一些你的HTML吗?以及如何/何时致电playerMove(piece)
  • 我建议您使用并更新一个数组,该数组描述了哪里有“Xs”、“Os”以及哪里有空白点。五回合或更多回合后,运行一个循环,在每回合之后检查所有 8 个选项是否获胜(它会足够快)。
  • window.setInterval("X", 10000);应该有一个函数/代码而不是字符串
  • @DerekAdair Programmers 并不是一个真正关于“通用建议”的网站,但关于软件开发和实施问题的概念性问题完全是题外话。我不认为“不确定参数是否包含对'piece'或a、b和c的引用”可以作为架构/设计问题传递,我真的不明白为什么这个问题会离题在堆栈溢出上。
  • @YannisRizos:绝对误读了 OP 的问题。我把它当作“我在这里做错了什么,design 怎么能更好?”。没有回答“我如何参考这些作品”这个问题。

标签: javascript html css


【解决方案1】:
<html>
<head>
<script type="text/javascript">
var cur_id;
var tempkeycode = "";
function setKeycode(input)
{
    tempkeycode = input;
    xowin()
}
function setId(id)
{
    cur_id = id;
    xowin()
}
function keyPress(e) 
{
    var input = e.keyCode ? e.keyCode : e.charCode;
    if(tempkeycode == "")
    {
        if ((input == 111) || (input == 120))
        {
            setKeycode(input);
            return true;
        }   
        else 
            return false;
    }
    else
    {
        if(((input == 111) || (input == 120)) && (input != tempkeycode))
        {
            setKeycode(input);
            return true;
        }
        else
        {
            return false;
        }
    }
}
function preventBackspace(e) 
{
    var evt = e || window.event;
        if (evt) 
        {
            var keyCode = evt.charCode || evt.keyCode;
            if (keyCode === 8) 
            {
                if (evt.preventDefault) 
                {
                    evt.preventDefault();
                } 
                else 
                {
                    evt.returnValue = false;
                }
            }
        }
}
function xowin()
{
tb1val = document.getElementById("tb1").value;
tb2val = document.getElementById("tb2").value;
tb3val = document.getElementById("tb3").value;
tb4val = document.getElementById("tb4").value;
tb5val = document.getElementById("tb5").value;
tb6val = document.getElementById("tb6").value;
tb7val = document.getElementById("tb7").value;
tb8val = document.getElementById("tb8").value;
tb9val = document.getElementById("tb9").value;

    if(tb1val == tb2val && tb2val == tb3val && tb1val!= "" && tb2val!= "" && tb3val!= "")
    {
        alert("Player "+tb1val+" Wins!!!");
    }
    else if(tb4val == tb5val && tb5val == tb6val && tb4val!= "" && tb5val!= "" && tb6val!= "")
    {
        alert("Player "+tb5val+" Wins!!!");
    }
    else if(tb7val == tb8val && tb8val == tb9val && tb7val!= "" && tb8val!= "" && tb9val!= "")
    {
        alert("Player "+tb7val+" Wins!!!");
    }
    else if(tb1val == tb4val && tb4val == tb7val && tb1val!= "" && tb4val!= "" && tb7val!= "")
    {
        alert("Player "+tb4val+" Wins!!!");
    }
    else if(tb2val == tb5val && tb5val == tb8val && tb2val!= "" && tb5val!= "" && tb8val!= "")
    {
        alert("Player "+tb2val+" Wins!!!");
    }
    else if(tb3val == tb6val && tb6val == tb9val && tb3val!= "" && tb6val!= "" && tb9val!= "")
    {
        alert("Player "+tb6val+" Wins!!!");
    }
    else if(tb1val == tb5val && tb5val == tb9val && tb1val!= "" && tb5val!= "" && tb9val!= "")
    {
        alert("Player "+tb9val+" Wins!!!");
    }
    else if(tb3val == tb5val && tb5val == tb7val && tb3val!= "" && tb5val!= "" && tb7val!= "")
    {
        alert("Player "+tb3val+" Wins!!!");
    }
    else
    {
        if(tb1val!= "" && tb2val!= "" && tb3val!= "" && tb4val!= "" && tb5val!= "" && tb6val!= "" && tb7val!= "" && tb8val!= "" && tb9val!= "")
        {
            alert("Draw");
        }
    }
}
</script>
</head>
<body bgcolor="blue">
<center>
    <h1>Tic Tac Toe</h1>
    <input type="text" id="tb1" value="" size="1" onkeydown="preventBackspace(event)" onkeypress="return keyPress(event)" onblur="setId(this.id);" maxlength="1">
    <input type="text" id="tb2" value="" size="1" onkeydown="preventBackspace(event)" onkeypress="return keyPress(event)" onblur="setId(this.id);" maxlength="1">
    <input type="text" id="tb3" value="" size="1" onkeydown="preventBackspace(event)" onkeypress="return keyPress(event)" onblur="setId(this.id);" maxlength="1"><br>
    <input type="text" id="tb4" value="" size="1" onkeydown="preventBackspace(event)" onkeypress="return keyPress(event)" onblur="setId(this.id);" maxlength="1">
    <input type="text" id="tb5" value="" size="1" onkeydown="preventBackspace(event)" onkeypress="return keyPress(event)" onblur="setId(this.id);" maxlength="1">
    <input type="text" id="tb6" value="" size="1" onkeydown="preventBackspace(event)" onkeypress="return keyPress(event)" onblur="setId(this.id);" maxlength="1"><br>
    <input type="text" id="tb7" value="" size="1" onkeydown="preventBackspace(event)" onkeypress="return keyPress(event)" onblur="setId(this.id);" maxlength="1">
    <input type="text" id="tb8" value="" size="1" onkeydown="preventBackspace(event)" onkeypress="return keyPress(event)" onblur="setId(this.id);" maxlength="1">
    <input type="text" id="tb9" value="" size="1" onkeydown="preventBackspace(event)" onkeypress="return keyPress(event)" onblur="setId(this.id);" maxlength="1"><br>
</center>
</body>
</html>

【讨论】:

    【解决方案2】:
    <html>
    <head>
    <script type="text/javascript">
    var currentvalue = "O";
    var b1 = "notClicked";
    var b2 = "notClicked";
    var b3 = "notClicked";
    var b4 = "notClicked";
    var b5 = "notClicked";
    var b6 = "notClicked";
    var b7 = "notClicked";
    var b8 = "notClicked";
    var b9 = "notClicked";
    function first()
    {
        if(b1== "notClicked")
        {
            if(currentvalue == "O")
                {
                currentvalue = "X";
                }
                document.getElementById("b1").value=currentvalue;
                b1 = "clicked";
            if(b5== "notClicked")
                {
                document.getElementById("b5").value="O";
                b5 = "clicked";
                }
            else if(b9== "notClicked")
                {
                document.getElementById("b9").value="O";
                b9 = "clicked";
                }
            else if(b4== "notClicked")
                {
                document.getElementById("b4").value="O";
                b4 = "clicked";
                }
            else if(b3== "notClicked")
                {
                document.getElementById("b3").value="O";
                b3 = "clicked";
                }
            else if(b2== "notClicked")
                {
                document.getElementById("b2").value="O";
                b2 = "clicked";
                }
            else if(b7== "notClicked")
                {
                document.getElementById("b7").value="O";
                b7 = "clicked";
                }
            else if(b8== "notClicked")
                {
                document.getElementById("b8").value="O";
                b8 = "clicked";
                }
            else if(b6=="notClicked")
                {
                document.getElementById("b6").value="O";
                b6 = "clicked";
                }
        }
        xowin()
    }
    function second()
    {
        if(b2== "notClicked")
        {
            if(currentvalue == "O")
                {
                currentvalue = "X";
                }
                document.getElementById("b2").value=currentvalue;
                b2 = "clicked";
            if(b5== "notClicked")
                {
                document.getElementById("b5").value="O";
                b5 = "clicked";
                }
            else if(b8== "notClicked")
                {
                document.getElementById("b8").value="O";
                b8 = "clicked";
                }
            else if(b4== "notClicked")
                {
                document.getElementById("b4").value="O";
                b4 = "clicked";
                }
            else if(b3== "notClicked")
                {
                document.getElementById("b3").value="O";
                b3 = "clicked";
                }
            else if(b9== "notClicked")
                {
                document.getElementById("b9").value="O";
                b9 = "clicked";
                }
            else if(b7== "notClicked")
                {
                document.getElementById("b7").value="O";
                b7 = "clicked";
                }
            else if(b1== "notClicked")
                {
                document.getElementById("b1").value="O";
                b1 = "clicked";
                }   
            else if(b6=="notClicked")
                {
                document.getElementById("b6").value="O";
                b6 = "clicked";
                }   
        }
        xowin()
    }
    function third()
    {
        if(b3== "notClicked")
        {
            if(currentvalue == "O")
                {
                currentvalue = "X";
                }
                document.getElementById("b3").value=currentvalue;
                b3 = "clicked";
            if(b5== "notClicked")
                {
                document.getElementById("b5").value="O";
                b5 = "clicked";
                }
            else if(b1== "notClicked")
                {
                document.getElementById("b1").value="O";
                b1 = "clicked";
                }
            else if(b4== "notClicked")
                {
                document.getElementById("b4").value="O";
                b4 = "clicked";
                }
            else if(b2== "notClicked")
                {
                document.getElementById("b2").value="O";
                b2 = "clicked";
                }
            else if(b9== "notClicked")
                {
                document.getElementById("b9").value="O";
                b9 = "clicked";
                }
            else if(b7== "notClicked")
                {
                document.getElementById("b7").value="O";
                b7 = "clicked";
                }
            else if(b8== "notClicked")
                {
                document.getElementById("b8").value="O";
                b8 = "clicked";
                }
            else if(b6=="notClicked")
                {
                document.getElementById("b6").value="O";
                b6 = "clicked";
                }   
        }
        xowin()
    }
    function fourth()
    {
        if(b4== "notClicked")
        {
            if(currentvalue == "O")
                {
                currentvalue = "X";
                }
                document.getElementById("b4").value=currentvalue;
                b4 = "clicked";
            if(b5== "notClicked")
                {
                document.getElementById("b5").value="O";
                b5 = "clicked";
                }
            else if(b6== "notClicked")
                {
                document.getElementById("b6").value="O";
                b6 = "clicked";
                }
            else if(b3== "notClicked")
                {
                document.getElementById("b3").value="O";
                b3 = "clicked";
                }
            else if(b2== "notClicked")
                {
                document.getElementById("b2").value="O";
                b2 = "clicked";
                }
            else if(b9== "notClicked")
                {
                document.getElementById("b9").value="O";
                b9 = "clicked";
                }
            else if(b7== "notClicked")
                {
                document.getElementById("b7").value="O";
                b7 = "clicked";
                }
            else if(b8== "notClicked")
                {
                document.getElementById("b8").value="O";
                b8 = "clicked";
                }
            else if(b1=="notClicked")
                {
                document.getElementById("b1").value="O";
                b1 = "clicked";
                }   
        }
        xowin()
    }
    function fifth()
    {
        if(b5== "notClicked")
        {
            if(currentvalue == "O")
                {
                currentvalue = "X";
                }
                document.getElementById("b5").value=currentvalue;
                b5 = "clicked";
            if(b3== "notClicked")
                {
                document.getElementById("b3").value="O";
                b3 = "clicked";
                }
            else if(b1== "notClicked")
                {
                document.getElementById("b1").value="O";
                b1 = "clicked";
                }
            else if(b4== "notClicked")
                {
                document.getElementById("b4").value="O";
                b4 = "clicked";
                }
            else if(b2== "notClicked")
                {
                document.getElementById("b2").value="O";
                b2 = "clicked";
                }
            else if(b9== "notClicked")
                {
                document.getElementById("b9").value="O";
                b9 = "clicked";
                }
            else if(b7== "notClicked")
                {
                document.getElementById("b7").value="O";
                b7 = "clicked";
                }
            else if(b8== "notClicked")
                {
                document.getElementById("b8").value="O";
                b8 = "clicked";
                }   
            else if(b6=="notClicked")
                {
                document.getElementById("b6").value="O";
                b6 = "clicked";
                }   
        }
        xowin()
    }
    function sixth()
    {
        if(b6== "notClicked")
        {
            if(currentvalue == "O")
                {
                currentvalue = "X";
                }
                document.getElementById("b6").value=currentvalue;
                b6 = "clicked";
            if(b3== "notClicked")
                {
                document.getElementById("b3").value="O";
                b3 = "clicked";
                }
            else if(b1== "notClicked")
                {
                document.getElementById("b1").value="O";
                b1 = "clicked";
                }
            else if(b4== "notClicked")
                {
                document.getElementById("b4").value="O";
                b4 = "clicked";
                }
            else if(b2== "notClicked")
                {
                document.getElementById("b2").value="O";
                b2 = "clicked";
                }
            else if(b9== "notClicked")
                {
                document.getElementById("b9").value="O";
                b9 = "clicked";
                }
            else if(b7== "notClicked")
                {
                document.getElementById("b7").value="O";
                b7 = "clicked";
                }
            else if(b8== "notClicked")
                {
                document.getElementById("b8").value="O";
                b8 = "clicked";
                }   
            else if(b5=="notClicked")
                {
                document.getElementById("b5").value="O";
                b5 = "clicked";
                }   
        }
        xowin()
    }
    function seventh()
    {
        if(b7== "notClicked")
        {
            if(currentvalue == "O")
                {
                currentvalue = "X";
                }
                document.getElementById("b7").value=currentvalue;
                b7 = "clicked";
            if(b3== "notClicked")
                {
                document.getElementById("b3").value="O";
                b3 = "clicked";
                }
            else if(b1== "notClicked")
                {
                document.getElementById("b1").value="O";
                b1 = "clicked";
                }
            else if(b6== "notClicked")
                {
                document.getElementById("b6").value="O";
                b6 = "clicked";
                }
            else if(b9== "notClicked")
                {
                document.getElementById("b9").value="O";
                b9 = "clicked";
                }
            else if(b4== "notClicked")
                {
                document.getElementById("b4").value="O";
                b4 = "clicked";
                }
            else if(b5== "notClicked")
                {
                document.getElementById("b5").value="O";
                b5 = "clicked";
                }
            else if(b8== "notClicked")
                {
                document.getElementById("b8").value="O";
                b8 = "clicked";
                }   
            else if(b2=="notClicked")
                {
                document.getElementById("b2").value="O";
                b2 = "clicked";
                }   
        }
        xowin()
    }
    function eight()
    {
        if(b8== "notClicked")
        {
            if(currentvalue == "O")
                {
                currentvalue = "X";
                }
                document.getElementById("b8").value=currentvalue;
                b8 = "clicked";
            if(b2== "notClicked")
                {
                document.getElementById("b2").value="O";
                b2 = "clicked";
                }
            else if(b1== "notClicked")
                {
                document.getElementById("b1").value="O";
                b1 = "clicked";
                }
            else if(b3== "notClicked")
                {
                document.getElementById("b3").value="O";
                b3 = "clicked";
                }
            else if(b9== "notClicked")
                {
                document.getElementById("b9").value="O";
                b9 = "clicked";
                }
            else if(b4== "notClicked")
                {
                document.getElementById("b4").value="O";
                b4 = "clicked";
                }
            else if(b7== "notClicked")
                {
                document.getElementById("b7").value="O";
                b7 = "clicked";
                }
            else if(b5== "notClicked")
                {
                document.getElementById("b5").value="O";
                b5 = "clicked";
                }   
            else if(b6=="notClicked")
                {
                document.getElementById("b6").value="O";
                b6 = "clicked";
                }   
        }
        xowin()
    }
    function ninth()
    {
        if(b9== "notClicked")
        {
            if(currentvalue == "O")
                {
                currentvalue = "X";
                }
                document.getElementById("b9").value=currentvalue;
                b9 = "clicked";
            if(b3== "notClicked")
                {
                document.getElementById("b3").value="O";
                b3 = "clicked";
                }
            else if(b1== "notClicked")
                {
                document.getElementById("b1").value="O";
                b1 = "clicked";
                }
            else if(b4== "notClicked")
                {
                document.getElementById("b4").value="O";
                b4 = "clicked";
                }
            else if(b2== "notClicked")
                {
                document.getElementById("b2").value="O";
                b2 = "clicked";
                }
            else if(b8== "notClicked")
                {
                document.getElementById("b8").value="O";
                b8 = "clicked";
                }
            else if(b7== "notClicked")
                {
                document.getElementById("b7").value="O";
                b7 = "clicked";
                }
            else if(b5== "notClicked")
                {
                document.getElementById("b5").value="O";
                b5 = "clicked";
                }   
            else if(b6=="notClicked")
                {
                document.getElementById("b6").value="O";
                b6 = "clicked";
                }   
        }
        xowin()
    }
    function xowin()
    {
    b1val = document.getElementById("b1").value;
    b2val = document.getElementById("b2").value;
    b3val = document.getElementById("b3").value;
    b4val = document.getElementById("b4").value;
    b5val = document.getElementById("b5").value;
    b6val = document.getElementById("b6").value;
    b7val = document.getElementById("b7").value;
    b8val = document.getElementById("b8").value;
    b9val = document.getElementById("b9").value;
    
        if(b1val == b2val && b2val == b3val && b1val!= "" && b2val!= "" && b3val!= "")
        {
            alert("Player "+b1val+" Wins!!!");
        }
        else if(b4val == b5val && b5val == b6val && b4val!= "" && b5val!= "" && b6val!= "")
        {
            alert("Player "+b5val+" Wins!!!");
        }
        else if(b7val == b8val && b8val == b9val && b7val!= "" && b8val!= "" && b9val!= "")
        {
            alert("Player "+b7val+" Wins!!!");
        }
        else if(b1val == b4val && b4val == b7val && b1val!= "" && b4val!= "" && b7val!= "")
        {
            alert("Player "+b4val+" Wins!!!");
        }
        else if(b2val == b5val && b5val == b8val && b2val!= "" && b5val!= "" && b8val!= "")
        {
            alert("Player "+b2val+" Wins!!!");
        }
        else if(b3val == b6val && b6val == b9val && b3val!= "" && b6val!= "" && b9val!= "")
        {
            alert("Player "+b6val+" Wins!!!");
        }
        else if(b1val == b5val && b5val == b9val && b1val!= "" && b5val!= "" && b9val!= "")
        {
            alert("Player "+b9val+" Wins!!!");
        }
        else if(b3val == b5val && b5val == b7val && b3val!= "" && b5val!= "" && b7val!= "")
        {
            alert("Player "+b3val+" Wins!!!");
        }
        else
        {
            if(b1val!= "" && b2val!= "" && b3val!= "" && b4val!= "" && b5val!= "" && b6val!= "" && b7val!= "" && b8val!= "" && b9val!= "")
            {
                alert("Draw");
            }
        }
    }
    </script>
    </head>
    <body bgcolor="lightblue">
    <h1 align="center">TIC TAC TOE</h1>
    <center>
        <input type="button" id="b1" onclick="first()">
        <input type="button" id="b2" onclick="second()">
        <input type="button" id="b3" onclick="third()"><br>
        <input type="button" id="b4" onclick="fourth()">
        <input type="button" id="b5" onclick="fifth()">
        <input type="button" id="b6" onclick="sixth()"><br>
        <input type="button" id="b7" onclick="seventh()">
        <input type="button" id="b8" onclick="eight()">
        <input type="button" id="b9" onclick="ninth()"><br>
        <input type="button" id="b10" value="New Game" onclick="history.go(0)">
    </center>
    </body>
    </html>
    

    【讨论】:

      【解决方案3】:

      亚瑟·伍尔夫·怀特怎么说:

      <html><head>
      <style>
      td{border:1px solid black;padding:0px;width:20px;height:22px;text-align:center}
      </style>
      <script>
      var s = "O"; 
      var r = [0,0,0,0,0,0,0,0,0];
      function t(a,b,c) {
       return (Math.abs(r[a] + r[b] + r[c]) == 3 ? true : false);
      }
      function a() {
       var c = document.getElementsByTagName("INPUT");
       for (var i = 0; i < c.length;i++) {
        if (c[i].checked == true) {
         var g = parseInt(c[i].id);
         r[g] = (s=="O" ? -1 : 1); 
         var m = document.createElement("TEXT");
         m.innerHTML = s;
         c[i].parentNode.replaceChild(m, c[i]);
         if (t(0,1,2) || t(3,4,5) || t(6,7,8) || t(0,3,6) || t(1,4,7) || t(2,5,8) || t(0,4,8) || t(2,4,6)) {
          alert("Player " + s + " wins!");
         }
         s = (s=="O" ? "X" : "O");
        }
       }
      }
      </script>
      </head><body>
      <table cellspacing='0' onclick='a()' name='board'>
      <tr><td><input type='checkbox' id='0' /></td><td><input type='checkbox' id='1' /></td><td><input type='checkbox' id='2' /></td></tr>
      <tr><td><input type='checkbox' id='3' /></td><td><input type='checkbox' id='4' /></td><td><input type='checkbox' id='5' /></td></tr>
      <tr><td><input type='checkbox' id='6' /></td><td><input type='checkbox' id='7' /></td><td><input type='checkbox' id='8' /></td></tr>
      </table>
      </body></html>
      

      方式又快又脏,但这是多么大的挑战!下次面试 JS 程序员的时候我会用这个!

      【讨论】:

      • 我会试试这个,看看我能得到什么。我需要使用没有表格的外部 javascript 文件(div 的唯一可用图)来编写这个,但我会解决这个问题,我会让你知道它是如何进行的。谢谢!
      【解决方案4】:

      const tokens = [{
          name: "Beemo",
          img: "beemo-token.png",
        },
        {
          name: "Princess Bubblegum",
          img: "bubble-token.png",
        }
      ]
      
      let player1 = {
        token: 0
      }
      
      let player2 = {
        token: 1
      }
      
      let gameboard = [
        [-1, -1, -1],
        [-1, -1, -1],
        [-1, -1, -1]
      ]; // array representation of gameboard
      let currentPlayer = 1; // indicates who's turn it is
      let numTurn = 0; // counts the num of turns made
      
      populateSpace();
      let againBtn = document.getElementById("again-btn");
      againBtn.addEventListener("click", playAgain);
      
      // Populates the spaces for the gameboard
      function populateSpace() {
        // <div class="space">&nbsp;</div>
        let rows = document.querySelectorAll(".row");
        // return [<div>, <div>, <div>]
        for (let rowNum = 0; rowNum < rows.length; rowNum++) {
          let row = rows[rowNum];
          for (let col = 0; col < 3; col++) {
            let space = document.createElement("div");
            space.innerHTML = "&nbsp;";
            space.classList.add("space");
            space.id = rowNum + "-" + col;
            space.addEventListener("click", playerTurn);
            row.appendChild(space);
          }
        }
      }
      
      // Implements functionality when a player turn is made
      function playerTurn(event) {
        let spaceContent = event.target;
        let location = spaceContent.id.split("-");
        let row = location[0];
        let col = location[1];
        // update the gameboard array ("placeToken")
        placeToken(row, col);
        // update the gameboard DOM
        updateGameboard();
        // check whether the current Player has won
        numTurn++;
        let won = checkWon();
        if (won) {
          report("Congratulations! Player " + currentPlayer + " has won!");
          return
        }
        if (numTurn == 9) {
          report("There was a tie");
          return
        }
        updateTurn();
        // if the player has not won => update the Turn
        // if the player has won/tie => show the container-div
      }
      
      // Updates the gameboard variable to indicate a token was placed at a specific row, col
      function placeToken(row, col) {
        if (gameboard[row][col] == -1) {
          if (currentPlayer == 1) {
            gameboard[row][col] = 1;
          } else { // currentPlayer == 2
            gameboard[row][col] = 2;
          }
        }
      }
      
      // Update who's turn it is
      function updateTurn() {
        if (currentPlayer == 1) {
          currentPlayer = 2;
        } else { // currentPlayer = 1
          currentPlayer = 1;
        }
        let turn = document.querySelector("span");
        turn.textContent = "Player " + currentPlayer;
      }
      
      // Updates the gameboard generating the tokens based on the gameboard values
      function updateGameboard() {
        for (let row = 0; row < 3; row++) {
          for (let col = 0; col < 3; col++) {
            let space = document.getElementById(row + "-" + col);
            space.innerHTML = "";
            if (gameboard[row][col] == 1) {
              let token = makeToken(player1);
              space.appendChild(token);
            } else if (gameboard[row][col] == 2) {
              let token = makeToken(player2);
              space.appendChild(token);
            } else { // gameboard[row][col] == -1
      
            }
          }
        }
      }
      
      // Creates and returns the token DOM element of the given player
      function makeToken(player) {
        let token = document.createElement("img");
        token.classList.add("token");
        token.src = "./img/tokens/" + tokens[player.token].img;
        token.alt = tokens[player.token].name;
        return token;
      }
      
      // Report whether the player has won or lost
      function report(message) {
        let winContainer = document.getElementById("win-container");
        let gameContainer = document.getElementById("gameboard");
        winContainer.classList.remove("hidden");
        gameContainer.classList.add("hidden");
      
        let h2 = document.querySelector("#win-container h2");
        h2.textContent = message;
      }
      
      // Restarts and shows the gameboard to play again
      function playAgain() {
        clearGameboard();
        let winContainer = document.getElementById("win-container");
        let gameContainer = document.getElementById("gameboard");
        winContainer.classList.add("hidden");
        gameContainer.classList.remove("hidden");
        numTurn = 0;
      }
      
      // Clears the gameboard
      function clearGameboard() {
        let rows = document.querySelectorAll(".row");
        for (let i = 0; i < rows.length; i++) {
          let row = rows[i];
          row.innerHTML = "";
        }
        gameboard = [
          [-1, -1, -1],
          [-1, -1, -1],
          [-1, -1, -1]
        ];
        populateSpace();
      }
      
      // Returns true/false if the current player who just made a move won
      function checkWon() {
        // Horizontal
        for (let row = 0; row < 3; row++) {
          let count = 0;
          for (let col = 0; col < 3; col++) {
            if (gameboard[row][col] == currentPlayer) {
              count++;
            }
          }
          if (count == 3) {
            return true;
          }
          count = 0;
        }
      
        // Vertical
        for (let col = 0; col < 3; col++) {
          let count = 0;
          for (let row = 0; row < 3; row++) {
            if (gameboard[row][col] == currentPlayer) {
              count++;
            }
          }
          if (count == 3) {
            return true;
          }
          count = 0;
        }
      
        // Diagonal
        if (gameboard[0][0] == currentPlayer &&
          gameboard[1][1] == currentPlayer &&
          gameboard[2][2] == currentPlayer) {
          return true;
        }
      
        if (gameboard[0][2] == currentPlayer &&
          gameboard[1][1] == currentPlayer &&
          gameboard[2][0] == currentPlayer) {
          return true;
        }
      
        return false
      }
      body {
        font-family: 'Ranchers', Arial, Helvetica, sans-serif;
        background-color: cornsilk;
      }
      
      button {
        background-color: lightblue;
        padding: 10px;
        border: 1px solid grey;
        border-radius: 5px;
      }
      
      .space {
        width: 200px;
        height: 200px;
        border: 1px solid black;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      
      .row {
        display: flex;
        justify-content: center;
      }
      
      h1,
      h2,
      p {
        text-align: center;
      }
      
      .hidden {
        display: none;
      }
      
      #win-container {
        border: 3px solid black;
        border-radius: 5px;
        padding: 15px;
        width: 80%;
        margin-left: auto;
        margin-right: auto;
      }
      
      #win-container button {
        display: block;
        margin-left: auto;
        margin-right: auto;
      }
      
      .token {
        max-width: 200px;
      }
      
      * {
        cursor: url("./img/uni.cur"), pointer;
      }
        <meta name="author" content="Elisa" />
        <link href="https://fonts.googleapis.com/css2?family=Ranchers&display=swap" rel="stylesheet">
        <link href="./style.css" rel="stylesheet" />
      
      <body>
        <h1>Tic Tac Toe Time</h1>
        <p>It's <span>Player 1</span> turn</p>
        <div id="gameboard">
          <div class="row"></div>
          <div class="row"></div>
          <div class="row"></div>
        </div>
        <div id="win-container" class="hidden">
          <h2>Hello</h2>
          <button id="again-btn">Play Again?</button>
        </div>
        <script src="index.js"></script>
      </body>

      我是用 Adventure-Time 代币而不是 Xs 和 Os 来做的。当然,您可以使用任何您想要的图像。只需记住更改 JS 和 HTML 中的图像名称/ID。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多