用html做个五子棋游戏完整代码
时间: 2024-05-26 16:06:56 浏览: 31
当然可以!以下是一个使用HTML、CSS和JavaScript实现的简单五子棋游戏的完整代码:
HTML部分:
```html
<!DOCTYPE html>
<html>
<head>
<title>五子棋游戏</title>
<style>
.board {
display: grid;
grid-template-columns: repeat(15, 1fr);
grid-template-rows: repeat(15, 1fr);
width: 500px;
height: 500px;
}
.cell {
border: 1px solid black;
background-color: #f5f5f5;
}
</style>
</head>
<body>
<div class="board" id="board"></div>
<script src="script.js"></script>
</body>
</html>
```
JavaScript部分(script.js):
```javascript
const board = document.getElementById('board');
const cells = [];
let currentPlayer = 'X';
for (let i = 0; i < 15; i++) {
for (let j = 0; j < 15; j++) {
const cell = document.createElement('div');
cell.classList.add('cell');
cell.addEventListener('click', () => makeMove(i, j));
board.appendChild(cell);
cells.push(cell);
}
}
function makeMove(row, col) {
const index = row * 15 + col;
if (cells[index].innerHTML === '') {
cells[index].innerHTML = currentPlayer;
cells[index].style.color = currentPlayer === 'X' ? 'black' : 'white';
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
}
}
```
CSS部分(可选,用于美化界面):
```css
.board {
display: grid;
grid-template-columns: repeat(15, 1fr);
grid-template-rows: repeat(15, 1fr);
width: 500px;
height: 500px;
}
.cell {
border: 1px solid black;
background-color: #f5f5f5;
}
```
这段代码创建了一个15x15的棋盘,每个格子都是一个可点击的div元素。当点击某个格子时,会在该格子上显示当前玩家的棋子('X'或'O'),并切换到下一个玩家。你可以根据需要进一步完善游戏规则和界面设计。
相关推荐
![html](https://img-home.csdnimg.cn/images/20210720083451.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)