const cells = document.querySelectorAll(".cell");
const winnerMessage = document.getElementById("winner-message");
const resetButton = document.getElementById("reset-button");
let currentPlayer = "〇";
let board = Array(9).fill(null);
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],
];
function checkWinner() {
for (const combination of winningCombinations) {
const [a, b, c] = combination;
if (board[a] && board[a] === board[b] && board[a] === board[c]) {
return board[a];
}
}
return board.includes(null) ? null : "引き分け";
}
function handleClick(event) {
const cell = event.target;
const index = cell.dataset.index;
if (board[index] === null) {
board[index] = currentPlayer;
cell.textContent = currentPlayer;
cell.classList.add("taken");
const winner = checkWinner();
if (winner) {
winnerMessage.textContent =
winner === "引き分け" ? "引き分けです!" : `${winner} の勝ち!`;
cells.forEach(cell => cell.classList.add("taken"));
} else {
currentPlayer = currentPlayer === "〇" ? "×" : "〇";
}
}
}
function resetGame() {
board.fill(null);
currentPlayer = "〇";
winnerMessage.textContent = "";
cells.forEach(cell => {
cell.textContent = "";
cell.classList.remove("taken");
});
}
cells.forEach(cell => cell.addEventListener("click", handleClick));
resetButton.addEventListener("click", resetGame);
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f7f7f7;
}
h1 {
color: #333;
}
#game-board {
display: grid;
grid-template-columns: repeat(3, 100px);
gap: 5px;
margin: 20px auto;
width: 310px;
}
.cell {
width: 100px;
height: 100px;
background-color: #fff;
border: 2px solid #ddd;
display: flex;
align-items: center;
justify-content: center;
font-size: 2rem;
cursor: pointer;
}
.cell.taken {
pointer-events: none;
}
#reset-button {
margin-top: 20px;
padding: 10px 20px;
font-size: 1rem;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
#reset-button:hover {
background-color: #0056b3;
}
#winner-message {
margin-top: 20px;
font-size: 1.2rem;
color: green;
}
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>〇×ゲーム</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>〇×ゲーム</h1>
<div id="game-board">
<div class="cell" data-index="0"></div>
<div class="cell" data-index="1"></div>
<div class="cell" data-index="2"></div>
<div class="cell" data-index="3"></div>
<div class="cell" data-index="4"></div>
<div class="cell" data-index="5"></div>
<div class="cell" data-index="6"></div>
<div class="cell" data-index="7"></div>
<div class="cell" data-index="8"></div>
</div>
<button id="reset-button">リセット</button>
<p id="winner-message"></p>
<script src="script.js"></script>
</body>
</html>