<template>
<div id="app">
<h1>Tic Tac Toe</h1>
<div class="board">
<div
v-for="(cell, index) in board"
:key="index"
class="cell"
@click="handleClick(index)"
>{{ cell }}</div>
</div>
<div class="status">
<p v-if="winner">Winner: {{ winner }}</p>
<p v-else-if="isBoardFull">It's a draw!</p>
<p v-else>Next Player: {{ currentPlayer }}</p>
</div>
<button @click="resetBoard">Reset Game</button>
</div>
</template>
<script>
export default {
data() {
return {
board: Array(9).fill(null),
currentPlayer: 'X',
winner: null
}
},
computed: {
isBoardFull() {
return this.board.every(cell => cell !== null)
}
},
methods: {
handleClick(index) {
if (!this.winner && !this.board[index] && !this.isBoardFull) {
this.board[index] = this.currentPlayer
this.currentPlayer = this.currentPlayer === 'X' ? 'O' : 'X'
this.checkWinner()
}
},
checkWinner() {
const winningCombos = [
[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 (const combo of winningCombos) {
const [a, b, c] = combo
if (
this.board[a] &&
this.board[a] === this.board[b] &&
this.board[a] === this.board[c]
) {
this.winner = this.currentPlayer
return alert('你获胜了!')
}
}
},
resetBoard() {
this.board = Array(9).fill(null)
this.currentPlayer = 'X'
this.winner = null
}
}
}
</script>
<style scoped>
.board {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-gap: 5px;
margin-top: 20px;
}
.cell {
width: 100px;
height: 100px;
display: flex;
justify-content: center;
align-items: center;
font-size: 24px;
background-color: #eee;
cursor: pointer;
}
.cell:hover {
background-color: #ddd;
}
.status {
margin-top: 20px;
}
button {
margin-top: 10px;
background-color: #007bff;
color: #fff;
padding: 10px 20px;
border: none;
cursor: pointer;
font-size: 18px;
}
button:hover {
background-color: #0056b3;
}
</style>