js五子棋怎么判断胜利
时间: 2023-12-11 13:04:34 浏览: 47
在 JavaScript 实现五子棋游戏中,判断胜利的方法通常是检查每行、每列和每条对角线上是否有五个连续的同色棋子。具体实现步骤如下:
1. 遍历棋盘的所有行和列,检查是否有连续的五个同色棋子。
2. 遍历棋盘的所有对角线(包括正斜线和反斜线),检查是否有连续的五个同色棋子。
3. 如果存在连续的五个同色棋子,则判定该颜色棋子获胜。
以下是一个简单的 JavaScript 函数实现:
```javascript
function checkWin(board, row, col, color) {
// 检查行
let count = 0;
for(let i = 0; i < board.length; i++) {
if(board[row][i] === color) {
count++;
} else {
count = 0;
}
if(count === 5) {
return true;
}
}
// 检查列
count = 0;
for(let i = 0; i < board.length; i++) {
if(board[i][col] === color) {
count++;
} else {
count = 0;
}
if(count === 5) {
return true;
}
}
// 检查正斜线
count = 0;
let i = row, j = col;
while(i > 0 && j > 0) {
i--;
j--;
}
while(i < board.length && j < board.length) {
if(board[i][j] === color) {
count++;
} else {
count = 0;
}
if(count === 5) {
return true;
}
i++;
j++;
}
// 检查反斜线
count = 0;
i = row;
j = col;
while(i > 0 && j < board.length - 1) {
i--;
j++;
}
while(i < board.length && j >= 0) {
if(board[i][j] === color) {
count++;
} else {
count = 0;
}
if(count === 5) {
return true;
}
i++;
j--;
}
// 没有获胜
return false;
}
```
其中,`board` 是一个二维数组表示棋盘,`row` 和 `col` 分别是最后一步棋子的行和列,`color` 是棋子的颜色(黑棋或白棋)。函数返回值为布尔类型,表示是否获胜。