给出代码
时间: 2023-07-09 21:13:53 浏览: 33
以下是一个使用Vue.js框架实现井字棋游戏的示例代码,仅供参考:
HTML代码:
```
<div id="app">
<div class="board">
<div v-for="(value, index) in board" :key="index" class="cell" :class="{ selected: value !== '' }" @click="selectCell(index)">
{{ value }}
</div>
</div>
<div class="message">{{ message }}</div>
</div>
```
CSS代码:
```
.board {
display: flex;
flex-wrap: wrap;
width: 300px;
height: 300px;
border: 1px solid black;
}
.cell {
display: flex;
align-items: center;
justify-content: center;
width: 100px;
height: 100px;
font-size: 3rem;
cursor: pointer;
border: 1px solid black;
}
.selected {
background-color: #ccc;
}
.message {
margin-top: 10px;
font-size: 1.5rem;
font-weight: bold;
}
```
JavaScript代码:
```
new Vue({
el: '#app',
data: {
board: ['', '', '', '', '', '', '', '', ''],
currentPlayer: 'X',
message: ''
},
methods: {
selectCell(index) {
if (this.board[index] === '') {
this.$set(this.board, index, this.currentPlayer);
if (this.checkWin()) {
this.message = `${this.currentPlayer} wins!`;
} else if (this.checkDraw()) {
this.message = 'Draw!';
} else {
this.currentPlayer = this.currentPlayer === 'X' ? 'O' : 'X';
}
}
},
checkWin() {
const lines = [
[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 < lines.length; i++) {
const [a, b, c] = lines[i];
if (this.board[a] !== '' && this.board[a] === this.board[b] && this.board[a] === this.board[c]) {
return true;
}
}
return false;
},
checkDraw() {
return this.board.every(cell => cell !== '');
}
}
});
```
这段代码实现了一个简单的井字棋游戏,使用了Vue.js框架、HTML、CSS和JavaScript。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)