帮我写一个五子棋游戏的HTML的代码
时间: 2024-05-14 11:17:51 浏览: 6
好的,以下是一个简单的五子棋游戏的 HTML 代码:
```
<!DOCTYPE html>
<html>
<head>
<title>五子棋游戏</title>
<style type="text/css">
#board {
width: 600px;
height: 600px;
margin: 0 auto;
border: 2px solid black;
position: relative;
}
#board div {
position: absolute;
width: 40px;
height: 40px;
border-radius: 50%;
background-color: white;
box-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
}
.black {
background-color: black;
}
.white {
background-color: white;
border: 2px solid black;
}
</style>
</head>
<body>
<div id="board">
<script type="text/javascript">
var board = [];
var turn = "black";
for (var y = 0; y < 15; y++) {
board[y] = [];
for (var x = 0; x < 15; x++) {
board[y][x] = "";
var piece = document.createElement("div");
piece.setAttribute("id", y + "_" + x);
piece.style.top = (y * 40 + 10) + "px";
piece.style.left = (x * 40 + 10) + "px";
piece.addEventListener("click", function() {
if (this.className == "") {
this.className = turn;
var coords = this.id.split("_");
board[coords[0]][coords[1]] = turn;
if (checkWin(coords[0], coords[1])) {
alert(turn + " wins!");
} else {
turn = (turn == "black") ? "white" : "black";
}
}
});
document.getElementById("board").appendChild(piece);
}
}
function checkWin(y, x) {
var count = 1;
var color = board[y][x];
var directions = [[-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [1, 1], [-1, 1], [1, -1]];
for (var i = 0; i < directions.length; i++) {
var dx = directions[i][1];
var dy = directions[i][0];
var ny = parseInt(y) + dy;
var nx = parseInt(x) + dx;
while (ny >= 0 && ny < 15 && nx >= 0 && nx < 15 && board[ny][nx] == color) {
count++;
ny += dy;
nx += dx;
}
}
return (count >= 5);
}
</script>
</div>
</body>
</html>
```
这段代码创建了一个 15x15 的棋盘,使用 div 元素表示棋子。通过 JavaScript 实现了下棋和胜利判断的逻辑。每个棋子占据 40x40 像素的空间,棋盘总共占据 600x600 像素的区域。棋盘的边框为 2 像素的黑色实线,棋子为白色实心圆形,黑子和白子的区别为颜色不同。