首页 > 解决方案 > HTML 中的井字棋盘

问题描述

我想问一个相当简单的问题:如何使用 HTML5 和 CSS3 编写井字游戏?这是我运行的代码:

HTML

<!DOCTYPE html>
<html>
   <head> 
      <title> Tic Tac Toe</title>
      <link rel="stylesheet" type="text/css" href="Tic Tac Toe.css" media="screen"/>
      <script type="text/javascript" src="Tic Tac Toe.js"></script>
      <meta charset= "utf-8"> 
      <meta name="viewport" content="width=device-width">
   </head>
   <body> 
      <div id="square1"></div>
      <div id="square2"></div>
      <div id="square3"></div>
      <div id="square4"></div>
      <div id="square5"></div>
      <div id="square6"></div>
      <div id="square7"></div>
      <div id="square8"></div>
      <div id="square9"></div>
   </body>
</html>

CSS

#square1 {
    background-color: yellow;
    width: 50px;
    height: 50px;
    margin-left: 700px;
    position: static;
}

#square2 {
    background-color: grey;
    width: 50px;
    height: 50px;
    margin-left: 700px;
    position: static;
}

#square3 {
    background-color: yellow;
    width: 50px;
    height: 50px;
    margin-left: 700px;
    position: static;
}

#square4 {
    background-color: grey;
    width: 50px;
    height: 50px;
    margin-bottom: -40px;
    
}

#square5 {
    background-color: yellow;
    width: 50px;
    height: 50px;
}

#square6 {
    background-color: grey;
    width: 50px;
    height: 50px;
}

#square7 {
    background-color: yellow;
    width: 50px;
    height: 50px;
}

#square8 {
    background-color: grey;
    width: 50px;
    height: 50px;
}

#square9 {
    background-color: yellow;
    width: 50px;
    height: 50px;
}

有人可以告诉我如何处理这些 div,这样我就可以像板一样将它们分组?我试着画了 9 个方格,然后把它们组合成一个板子。但我不能,当我试图将一个 div 移到另一个附近时,它就会消失。我真的需要帮助:)))

另外,我注意到大多数人都用 JavaScript 编写代码。尝试用 CSS3 和 HTML 编写代码是否让我的生活变得更加困难?:D

提前非常感谢!

标签: javascripthtmlcsstic-tac-toe

解决方案


您可以使用 CSS flexbox 样式将 9 个盒子排列成 3 行。对于交替的背景颜色,您可以使用oddevenCSS 关键字。最好不要给每个盒子一个单独的id属性。而是将这些框组合在一个容器元素中,您可以在其中控制 CSS 样式及其子元素。

我添加了一点 JavaScript,只是为了说明如何在这些div元素中放置 X 和 O 符号。但仅此而已:

let game = document.getElementById("game");
let moveCount = 0;
game.addEventListener("click", function (e) {
    if (e.target.textContent) return; // is already occupied;
    e.target.textContent = "XO"[moveCount++ % 2];
});
#game {
    display: flex;
    flex-wrap: wrap; 
    width: 150px;
    font-size: 20px;
    text-align: center;
    line-height: 50px;
}

#game div {
    width: 50px;
    height: 50px;
    display: inline-block;
}

#game div:nth-child(odd) {
    background-color: yellow;
}

#game div:nth-child(even) {
    background-color: grey;
}
<div id="game">
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
</div>      

要添加游戏逻辑,例如检查是赢还是平,以及将“计算机”作为对手,请查看 Tic Tac Toe 上的其他一些问题,包括我发布答案的问题


推荐阅读