用html5语言写个小游戏吧
时间: 2023-08-30 20:10:57 浏览: 33
好的,我可以为您提供一个简单的井字棋游戏的示例。您可以在网页上玩这个游戏,也可以在本地运行。这是一个基于HTML5和JavaScript的实现。以下是代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>Tic Tac Toe Game</title>
<style>
.board {
display: flex;
flex-wrap: wrap;
width: 300px;
height: 300px;
margin: 0 auto;
background-color: #f2f2f2;
}
.cell {
box-sizing: border-box;
border: 1px solid #ccc;
width: calc(100%/3 - 2px);
height: calc(100%/3 - 2px);
font-size: 60px;
text-align: center;
line-height: calc(100%/3 - 2px);
cursor: pointer;
}
.cell:hover {
background-color: #ddd;
}
</style>
</head>
<body>
<h1>Tic Tac Toe</h1>
<div class="board"></div>
<script>
// 初始化游戏面板
const board = document.querySelector('.board');
let currentPlayer = 'X';
let cells = [];
for (let i = 0; i < 9; i++) {
let cell = document.createElement('div');
cell.className = 'cell';
cell.setAttribute('data-index', i);
cell.addEventListener('click', handleCellClick);
cells.push(cell);
board.appendChild(cell);
}
// 处理玩家点击事件
function handleCellClick(event) {
let cell = event.target;
if (cell.textContent !== '') {
alert('该位置已经有棋子了!');
return;
}
cell.textContent = currentPlayer;
if (checkWin()) {
alert(currentPlayer + ' 获胜!');
reset();
return;
}
if (checkTie()) {
alert('平局!');
reset();
return;
}
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
}
// 检查是否有一方获胜
function checkWin() {
let 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 line of lines) {
let [a, b, c] = line;
if (cells[a].textContent !== '' &&
cells[a].textContent === cells[b].textContent &&
cells[a].textContent === cells[c].textContent) {
return true;
}
}
return false;
}
// 检查是否为平局
function checkTie() {
for (let cell of cells) {
if (cell.textContent === '') {
return false;
}
}
return true;
}
// 重置游戏
function reset() {
for (let cell of cells) {
cell.textContent = '';
}
currentPlayer = 'X';
}
</script>
</body>
</html>
```
这个井字棋游戏可以让玩家轮流下棋,直到有一方连成一条线或者棋盘被填满。玩家可以在网页上点击棋盘上的格子来下棋。当有一方获胜或者棋盘被填满时,游戏将被重置。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)