返回

井字棋游戏 HTML CSS JS 开发

前端

井字棋作为我们在上学时代必玩的一款连珠游戏,你知道如何做到先手必然不会输吗?今天我们就用HTML、css、js来实现一款井字棋游戏。

工具和技术

  1. HTML
  2. CSS
  3. JavaScript
  4. 浏览器

HTML结构

<!DOCTYPE html>
<html>
<head>
  
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h1>井字棋游戏</h1>
  <div class="board">
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
  </div>
  <script src="script.js"></script>
</body>
</html>

CSS样式

.board {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  width: 300px;
  height: 300px;
  margin: 0 auto;
  border: 1px solid black;
}

.cell {
  width: 100px;
  height: 100px;
  border: 1px solid black;
}

.x {
  color: red;
  font-size: 50px;
}

.o {
  color: blue;
  font-size: 50px;
}

JavaScript代码

const cells = document.querySelectorAll('.cell');
let turn = 'X';

for (let i = 0; i < cells.length; i++) {
  cells[i].addEventListener('click', function() {
    if (this.textContent === '') {
      this.textContent = turn;
      if (turn === 'X') {
        turn = 'O';
      } else {
        turn = 'X';
      }
      checkWinner();
    }
  });
}

function checkWinner() {
  const winningCombinations = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6]
  ];

  for (let i = 0; i < winningCombinations.length; i++) {
    const combination = winningCombinations[i];
    if (cells[combination[0]].textContent === cells[combination[1]].textContent && cells[combination[1]].textContent === cells[combination[2]].textContent && cells[combination[0]].textContent !== '') {
      alert('Winner is ' + cells[combination[0]].textContent);
      return;
    }
  }
}

规则

  1. 游戏由两人轮流进行,分别使用“X”和“O”作为记号。
  2. 每个人轮流在一个空方格中放置自己的记号。
  3. 第一个将三个记号连成一条直线的人获胜。
  4. 直线可以是水平的、垂直的或对角线的。
  5. 如果所有方格都被填满而没有出现三连,则游戏以平局结束。

实现要点

  1. 使用 HTML 创建游戏界面。
  2. 使用 CSS 为游戏界面添加样式。
  3. 使用 JavaScript 处理用户交互和确定获胜者。

挑战

  1. 允许用户选择先手或后手。
  2. 在游戏中增加计时器。
  3. 添加音效和动画。
  4. 将游戏扩展为在线多人游戏。