js 五子棋 代码
时间: 2023-09-12 22:07:42 浏览: 77
以下是一个简单的JavaScript五子棋游戏代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>五子棋游戏</title>
<style>
#board {
width: 600px;
height: 600px;
border: 1px solid black;
position: relative;
}
.piece {
width: 40px;
height: 40px;
border-radius: 50%;
position: absolute;
top: 0;
left: 0;
background-color: white;
cursor: pointer;
}
.piece.black {
background-color: black;
}
.piece.white {
background-color: white;
}
</style>
</head>
<body>
<div id="board"></div>
<script>
var board = document.getElementById('board');
var pieces = [];
var currentPlayer = 'black';
var gameOver = false;
// 初始化棋盘
for (var i = 0; i < 15; i++) {
pieces[i] = [];
for (var j = 0; j < 15; j++) {
var piece = document.createElement('div');
piece.className = 'piece';
piece.dataset.row = i;
piece.dataset.col = j;
board.appendChild(piece);
piece.addEventListener('click', function() {
if (gameOver) {
return;
}
if (this.className.indexOf('black') >= 0 || this.className.indexOf('white') >= 0) {
return;
}
this.className += ' ' + currentPlayer;
pieces[this.dataset.row][this.dataset.col] = currentPlayer;
if (checkWin(this.dataset.row, this.dataset.col)) {
alert(currentPlayer + ' wins!');
gameOver = true;
} else {
currentPlayer = currentPlayer == 'black' ? 'white' : 'black';
}
});
}
}
// 检查是否获胜
function checkWin(row, col) {
var count = 1;
var r = row;
var c = col;
while (r - 1 >= 0 && pieces[r - 1][c] == currentPlayer) {
count++;
r--;
}
r = row;
c = col;
while (r + 1 < 15 && pieces[r + 1][c] == currentPlayer) {
count++;
r++;
}
if (count >= 5) {
return true;
}
count = 1;
r = row;
c = col;
while (c - 1 >= 0 && pieces[r][c - 1] == currentPlayer) {
count++;
c--;
}
r = row;
c = col;
while (c + 1 < 15 && pieces[r][c + 1] == currentPlayer) {
count++;
c++;
}
if (count >= 5) {
return true;
}
count = 1;
r = row;
c = col;
while (r - 1 >= 0 && c - 1 >= 0 && pieces[r - 1][c - 1] == currentPlayer) {
count++;
r--;
c--;
}
r = row;
c = col;
while (r + 1 < 15 && c + 1 < 15 && pieces[r + 1][c + 1] == currentPlayer) {
count++;
r++;
c++;
}
if (count >= 5) {
return true;
}
count = 1;
r = row;
c = col;
while (r - 1 >= 0 && c + 1 < 15 && pieces[r - 1][c + 1] == currentPlayer) {
count++;
r--;
c++;
}
r = row;
c = col;
while (r + 1 < 15 && c - 1 >= 0 && pieces[r + 1][c - 1] == currentPlayer) {
count++;
r++;
c--;
}
if (count >= 5) {
return true;
}
return false;
}
</script>
</body>
</html>
```
这段代码实现了一个简单的五子棋游戏,使用HTML和CSS构建了一个棋盘,使用JavaScript实现了落子、判断胜负等功能。
阅读全文