五子棋
五子棋 - 人机对弈产品介绍
产品简介
五子棋 - 人机对弈是一款基于HTML5技术开发的在线五子棋游戏,支持人机对弈和人人对弈两种模式。游戏界面美观简洁,操作流畅,AI智能强大,为玩家提供了一个高质量的五子棋对战平台。
核心功能
1. 多种游戏模式
- 人机对弈:与智能AI进行对战,AI会根据棋局情况做出最优决策
- 人人对弈:通过关闭AI开关,实现两人轮流在同一设备上对战
2. 智能AI
- 采用 minimax 算法结合 alpha-beta 剪枝,提高AI决策效率
- 支持威胁检测,能够识别并优先处理活三、冲四等关键局势
- 黑子禁手检测,确保AI遵守五子棋规则
3. 游戏功能
- 棋子颜色选择:玩家可以选择黑棋或白棋
- 悔棋功能:支持撤销上一步操作
- 重新开始:随时可以开始新的游戏
- 棋局导出/导入:通过字符串保存和恢复棋局状态
- 规则查看:内置详细的五子棋规则说明
4. 视觉体验
- 美观的棋盘设计,传统木质棋盘风格
- 清晰的棋子视觉效果,黑子和白子对比明显
- 上一步棋子标记,方便玩家追踪棋局进展
- 响应式布局,适配不同屏幕尺寸
游戏特色
- AI强度:AI能够识别各种威胁和机会,提供具有挑战性的对战体验
- 规则完整:支持黑子禁手规则,包括三三禁手、四四禁手和长连禁手
- 操作便捷:简单直观的界面设计,一键开始游戏,点击落子
- 功能丰富:提供完整的游戏辅助功能,满足玩家各种需求
- 无需安装:基于浏览器运行,无需下载安装任何软件
玩法说明
-
开始游戏:
- 选择棋子颜色(黑棋或白棋)
- 点击"开始游戏"按钮
- 如果选择白棋,AI会先行落子
-
落子:
- 点击棋盘上的空位落下你的棋子
- 黑棋有禁手规则,不能在禁手位置落子
-
胜负判定:
- 率先在一条直线(横、竖、斜)上形成五个同色棋子相连的一方获胜
- 如果棋盘填满仍未分胜负,则为平局
-
辅助功能:
- 悔棋:撤销上一步操作
- 重新开始:开始新的游戏
- 导出/导入:保存和恢复棋局
- 查看规则:了解五子棋规则
技术特点
- 前端技术:HTML5 + CSS3 + JavaScript
- AI算法:Minimax 算法 + Alpha-Beta 剪枝
- 响应式设计:适配不同屏幕尺寸
- 本地存储:使用浏览器本地存储保存游戏状态
- 模块化代码:清晰的代码结构,易于维护和扩展
适用人群
- 五子棋爱好者:享受高质量的对战体验
- 休闲玩家:在空闲时间放松娱乐
- AI研究者:了解AI在棋类游戏中的应用
- 教育工作者:作为教学工具,教授五子棋规则和策略
- 所有年龄段:简单易上手,适合各个年龄段的玩家
结语
五子棋 - 人机对弈是一款集娱乐性、挑战性和教育性于一体的在线游戏。无论是想提高棋艺,还是单纯享受游戏乐趣,都能在这款游戏中找到满足。智能的AI、完整的规则和丰富的功能,使其成为五子棋爱好者的理想选择。
立即开始你的五子棋之旅,挑战智能AI,体验传统棋类游戏的魅力! ::::info[HTML代码]
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>五子棋 - 人机对弈</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
}
h1 {
color: #333;
margin-bottom: 20px;
}
.game-container {
display: flex;
gap: 30px;
align-items: flex-start;
}
.board {
width: 450px;
height: 450px;
background-color: #f0c987;
border: 2px solid #8b4513;
position: relative;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.grid {
width: 100%;
height: 100%;
display: grid;
grid-template-columns: repeat(15, 1fr);
grid-template-rows: repeat(15, 1fr);
}
.cell {
width: 100%;
height: 100%;
border: 1px solid #8b4513;
cursor: pointer;
position: relative;
}
.cell:hover {
background-color: rgba(139, 69, 19, 0.1);
}
.piece {
position: absolute;
width: 80%;
height: 80%;
border-radius: 50%;
top: 10%;
left: 10%;
box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}
.piece.black {
background-color: #000;
}
.piece.white {
background-color: #fff;
border: 1px solid #ccc;
}
.piece.last-move {
border: 2px solid #f00;
}
.info-panel {
width: 200px;
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.status {
font-size: 18px;
font-weight: bold;
margin-bottom: 20px;
text-align: center;
}
.player-info {
margin-bottom: 15px;
}
.player-info .label {
font-size: 14px;
color: #666;
margin-bottom: 5px;
}
.player-info .value {
font-size: 16px;
font-weight: bold;
}
.controls {
margin-top: 20px;
}
button {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
font-weight: bold;
transition: background-color 0.3s;
}
.restart-btn {
background-color: #4CAF50;
color: white;
}
.restart-btn:hover {
background-color: #45a049;
}
.undo-btn {
background-color: #f44336;
color: white;
}
.undo-btn:hover {
background-color: #da190b;
}
.difficulty {
margin-top: 15px;
}
.difficulty label {
display: block;
margin-bottom: 5px;
font-size: 14px;
color: #666;
}
.difficulty select {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 14px;
}
.winner {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.7);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
z-index: 1000;
}
.winner-message {
background-color: white;
padding: 40px;
border-radius: 10px;
text-align: center;
box-shadow: 0 4px 20px rgba(0,0,0,0.3);
}
.winner-message h2 {
font-size: 24px;
margin-bottom: 20px;
color: #333;
}
.winner-message button {
width: auto;
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
.winner-message button:hover {
background-color: #45a049;
}
.rules {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.7);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.rules-content {
background-color: white;
padding: 30px;
border-radius: 10px;
width: 80%;
max-width: 600px;
max-height: 80%;
overflow-y: auto;
box-shadow: 0 4px 20px rgba(0,0,0,0.3);
}
.rules-content h2 {
text-align: center;
margin-bottom: 20px;
color: #333;
}
.rules-content h3 {
margin-top: 20px;
margin-bottom: 10px;
color: #555;
}
.rules-content p {
margin-bottom: 8px;
line-height: 1.5;
color: #666;
}
.rules-content button {
display: block;
margin: 20px auto 0;
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
.rules-content button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<h1>五子棋 - 人机对弈</h1>
<div class="game-container">
<div class="board">
<div class="grid" id="grid"></div>
</div>
<div class="info-panel">
<div class="status" id="status">选择棋子颜色</div>
<div class="player-info">
<div class="label">当前玩家</div>
<div class="value" id="current-player">黑棋</div>
</div>
<div class="color-selection">
<div class="label">选择棋子颜色</div>
<div style="display: flex; gap: 20px; margin: 10px 0; justify-content: center;">
<button onclick="selectColor(1)" style="width: 80px; height: 80px; border-radius: 50%; background-color: black; color: white; font-size: 14px; cursor: pointer;">黑棋</button>
<button onclick="selectColor(2)" style="width: 80px; height: 80px; border-radius: 50%; background-color: white; color: black; border: 2px solid #ccc; font-size: 14px; cursor: pointer;">白棋</button>
</div>
<div id="selected-color" style="text-align: center; margin: 10px 0;">已选择:黑棋</div>
</div>
<div class="rule">
<label for="forbidden-moves">黑子禁手</label>
<input type="checkbox" id="forbidden-moves" onchange="toggleForbiddenMoves()" checked>
</div>
<div class="rule">
<label for="ai-enabled">启用AI</label>
<input type="checkbox" id="ai-enabled" onchange="toggleAI()" checked>
</div>
<div class="controls">
<button class="start-btn" onclick="startGame()" style="width: 100%; padding: 10px; font-size: 16px; background-color: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer;">开始游戏</button>
<button class="restart-btn" onclick="restartGame()" style="width: 100%; margin-top: 10px; padding: 10px; font-size: 16px; background-color: #f44336; color: white; border: none; border-radius: 4px; cursor: pointer;">重新开始</button>
<button class="undo-btn" onclick="undoMove()" style="width: 100%; margin-top: 10px; padding: 10px; font-size: 16px; background-color: #2196F3; color: white; border: none; border-radius: 4px; cursor: pointer;">悔棋</button>
<button class="rules-btn" onclick="showRules()" style="width: 100%; margin-top: 10px; padding: 10px; font-size: 16px; background-color: #9C27B0; color: white; border: none; border-radius: 4px; cursor: pointer;">查看规则</button>
</div>
<div class="game-export">
<button class="export-btn" onclick="exportGame()" style="width: 100%; padding: 8px; margin-top: 10px;">导出棋局</button>
<input type="text" id="import-input" placeholder="输入棋局字符串" style="width: 100%; margin: 10px 0; padding: 8px;">
<button class="import-btn" onclick="importGame()" style="width: 100%; padding: 8px;">导入棋局</button>
</div>
</div>
</div>
<div class="winner" id="winner" style="display: none;">
<div class="winner-message">
<h2 id="winner-text">黑棋获胜!</h2>
<button onclick="restartGame()">再来一局</button>
</div>
</div>
<div class="rules" id="rules" style="display: none;">
<div class="rules-content">
<h2>五子棋规则</h2>
<div class="rules-text">
<h3>基本规则</h3>
<p>1. 五子棋是一种两人对弈的纯策略型棋类游戏,黑白双方交替落子。</p>
<p>2. 率先在一条直线(横、竖、斜)上形成五个同色棋子相连的一方获胜。</p>
<p>3. 黑方先手,白方后手。</p>
<h3>禁手规则</h3>
<p>1. 黑子禁手:黑棋不能在一步棋中同时形成两个或以上的活三(三三禁手)。</p>
<p>2. 黑子禁手:黑棋不能在一步棋中同时形成两个或以上的四(四四禁手)。</p>
<p>3. 黑子禁手:黑棋不能形成长连(超过五连子)。</p>
<p>4. 白棋无禁手。</p>
<h3>活三与活四</h3>
<p>1. 活三:在一条直线上有三个同色棋子,并且可以找到一个空位落子形成活四。</p>
<p>2. 活四:在一条直线上有四个同色棋子,两端都没有被对方棋子堵住,两边都能下子成五。</p>
<p>3. 冲四:在一条直线上有四个同色棋子,一端被对方棋子堵住,另一端能下子成五。</p>
<h3>操作说明</h3>
<p>1. 选择棋子颜色:点击黑棋或白棋按钮选择你要使用的棋子颜色。</p>
<p>2. 开始游戏:选择颜色后点击开始游戏按钮开始游戏。</p>
<p>3. 落子:点击棋盘上的空位落下你的棋子。</p>
<p>4. 悔棋:点击悔棋按钮可以撤销上一步的操作。</p>
<p>5. 重新开始:点击重新开始按钮可以开始新的游戏。</p>
<p>6. 导出/导入:可以导出当前棋局为字符串,或导入字符串恢复棋局。</p>
</div>
<button onclick="hideRules()">关闭</button>
</div>
</div>
<script>
// 棋盘大小
const BOARD_SIZE = 15;
// 棋子类型
const EMPTY = 0;
const BLACK = 1;
const WHITE = 2;
// 游戏状态
let board = Array(BOARD_SIZE).fill().map(() => Array(BOARD_SIZE).fill(EMPTY));
let currentPlayer = BLACK;
let gameOver = false;
let gameStarted = false; // 游戏是否已经开始
let moveHistory = [];
let playerColor = BLACK;
let aiColor = WHITE;
let forbiddenMovesEnabled = true; // 黑子禁手模式
let aiEnabled = true; // AI启用状态
let lastMove = null; // 上一步的位置
// 初始化棋盘
function initBoard() {
const grid = document.getElementById('grid');
grid.innerHTML = '';
for (let i = 0; i < BOARD_SIZE; i++) {
for (let j = 0; j < BOARD_SIZE; j++) {
const cell = document.createElement('div');
cell.classList.add('cell');
cell.dataset.row = i;
cell.dataset.col = j;
cell.onclick = () => handleCellClick(i, j);
grid.appendChild(cell);
}
}
}
// 页面加载完成后初始化
window.onload = function() {
initBoard();
updateStatus();
// 开始游戏前隐藏导出,显示导入
document.querySelector('.export-btn').style.display = 'none';
document.getElementById('import-input').style.display = 'block';
document.querySelector('.import-btn').style.display = 'block';
}
// 选择颜色
function selectColor(color) {
playerColor = color;
aiColor = color === BLACK ? WHITE : BLACK;
currentPlayer = BLACK; // 黑棋始终先手
// 更新选择颜色的显示
const selectedColorElement = document.getElementById('selected-color');
selectedColorElement.textContent = `已选择:${color === BLACK ? '黑棋' : '白棋'}`;
updateStatus();
}
// 开始游戏
function startGame() {
// 标记游戏开始
gameStarted = true;
// 隐藏颜色选择和开始游戏按钮
document.querySelector('.color-selection').style.display = 'none';
document.querySelector('.start-btn').style.display = 'none';
// 开始游戏后隐藏导入,显示导出
document.querySelector('.import-btn').style.display = 'none';
document.getElementById('import-input').style.display = 'none';
document.querySelector('.export-btn').style.display = 'block';
// 如果玩家选择白棋,AI先落子
if (playerColor === WHITE && aiEnabled) {
setTimeout(() => {
aiMove();
}, 500);
}
updateStatus();
}
// 处理单元格点击
function handleCellClick(row, col) {
if (gameOver || !gameStarted || board[row][col] !== EMPTY) return;
// 确定当前落子的玩家
let currentPlayerToMove = currentPlayer;
// 检查是否为禁手
if (isForbiddenMove(row, col, currentPlayerToMove)) {
alert('禁手位置,不能下这里!');
return;
}
// 落子
placePiece(row, col, currentPlayerToMove);
moveHistory.push({row, col, player: currentPlayerToMove});
// 检查胜负
if (checkWin(row, col, currentPlayerToMove)) {
showWinner(currentPlayerToMove === BLACK ? '黑棋' : '白棋');
return;
}
// 检查平局
if (isBoardFull()) {
showWinner('平局');
return;
}
// 切换玩家
if (aiEnabled) {
// AI启用,切换到AI回合
currentPlayer = currentPlayerToMove === BLACK ? WHITE : BLACK;
updateStatus();
// AI落子
setTimeout(() => {
aiMove();
}, 500);
} else {
// AI禁用,切换到另一个玩家回合
currentPlayer = currentPlayerToMove === BLACK ? WHITE : BLACK;
updateStatus();
}
}
// 放置棋子
function placePiece(row, col, player) {
// 移除上一步的标记
if (lastMove) {
const lastCell = document.querySelector(`[data-row="${lastMove.row}"][data-col="${lastMove.col}"]`);
const lastPiece = lastCell.querySelector('.piece');
if (lastPiece) {
lastPiece.classList.remove('last-move');
}
}
board[row][col] = player;
const cell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
const piece = document.createElement('div');
piece.classList.add('piece');
piece.classList.add(player === BLACK ? 'black' : 'white');
piece.classList.add('last-move'); // 标记当前落子为上一步
cell.appendChild(piece);
// 更新上一步的位置
lastMove = { row, col };
// 更新状态
updateStatus();
}
// 更新状态
function updateStatus() {
const status = document.getElementById('status');
const currentPlayerEl = document.getElementById('current-player');
if (gameOver) {
status.textContent = '游戏结束';
} else {
const playerText = currentPlayer === BLACK ? '黑棋' : '白棋';
status.textContent = `轮到${playerText}`;
currentPlayerEl.textContent = playerText;
}
}
// 检查胜负
function checkWin(row, col, player) {
// 检查横向
let count = 1;
for (let j = col - 1; j >= 0 && board[row][j] === player; j--) count++;
for (let j = col + 1; j < BOARD_SIZE && board[row][j] === player; j++) count++;
if (count >= 5) return true;
// 检查纵向
count = 1;
for (let i = row - 1; i >= 0 && board[i][col] === player; i--) count++;
for (let i = row + 1; i < BOARD_SIZE && board[i][col] === player; i++) count++;
if (count >= 5) return true;
// 检查左上到右下
count = 1;
for (let i = row - 1, j = col - 1; i >= 0 && j >= 0 && board[i][j] === player; i--, j--) count++;
for (let i = row + 1, j = col + 1; i < BOARD_SIZE && j < BOARD_SIZE && board[i][j] === player; i++, j++) count++;
if (count >= 5) return true;
// 检查右上到左下
count = 1;
for (let i = row - 1, j = col + 1; i >= 0 && j < BOARD_SIZE && board[i][j] === player; i--, j++) count++;
for (let i = row + 1, j = col - 1; i < BOARD_SIZE && j >= 0 && board[i][j] === player; i++, j--) count++;
if (count >= 5) return true;
return false;
}
// 检查棋盘是否已满
function isBoardFull() {
for (let i = 0; i < BOARD_SIZE; i++) {
for (let j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] === EMPTY) return false;
}
}
return true;
}
// 显示获胜者
function showWinner(winner) {
gameOver = true;
const winnerEl = document.getElementById('winner');
const winnerTextEl = document.getElementById('winner-text');
winnerTextEl.textContent = winner === '平局' ? '平局!' : `${winner}获胜!`;
winnerEl.style.display = 'flex';
updateStatus();
}
// 重新开始游戏
function restartGame() {
board = Array(BOARD_SIZE).fill().map(() => Array(BOARD_SIZE).fill(EMPTY));
currentPlayer = BLACK;
gameOver = false;
gameStarted = false; // 重置游戏开始状态
moveHistory = [];
playerColor = BLACK;
aiColor = WHITE;
lastMove = null;
initBoard();
updateStatus();
document.getElementById('winner').style.display = 'none';
// 显示颜色选择和开始游戏按钮
document.querySelector('.color-selection').style.display = 'block';
document.querySelector('.start-btn').style.display = 'block';
// 开始游戏前隐藏导出,显示导入
document.querySelector('.export-btn').style.display = 'none';
document.getElementById('import-input').style.display = 'block';
document.querySelector('.import-btn').style.display = 'block';
}
// 悔棋
function undoMove() {
if (moveHistory.length === 0 || gameOver) return;
// 撤销玩家的最后一步
const lastMove = moveHistory.pop();
board[lastMove.row][lastMove.col] = EMPTY;
const cell = document.querySelector(`[data-row="${lastMove.row}"][data-col="${lastMove.col}"]`);
cell.innerHTML = '';
// 如果AI也下了一步,也撤销
if (moveHistory.length > 0) {
const aiMove = moveHistory.pop();
board[aiMove.row][aiMove.col] = EMPTY;
const aiCell = document.querySelector(`[data-row="${aiMove.row}"][data-col="${aiMove.col}"]`);
aiCell.innerHTML = '';
}
// 更新上一步的位置
if (moveHistory.length > 0) {
window.lastMove = moveHistory[moveHistory.length - 1];
// 为新的上一步添加标记
const lastCell = document.querySelector(`[data-row="${window.lastMove.row}"][data-col="${window.lastMove.col}"]`);
const lastPiece = lastCell.querySelector('.piece');
if (lastPiece) {
lastPiece.classList.add('last-move');
}
} else {
window.lastMove = null;
}
currentPlayer = BLACK;
gameOver = false;
updateStatus();
}
// AI落子
function aiMove() {
if (gameOver || !aiEnabled) return;
const bestMove = findBestMove();
placePiece(bestMove.row, bestMove.col, aiColor);
moveHistory.push({row: bestMove.row, col: bestMove.col, player: aiColor});
// 检查胜负
if (checkWin(bestMove.row, bestMove.col, aiColor)) {
showWinner(aiColor === BLACK ? '黑棋' : '白棋');
return;
}
// 检查平局
if (isBoardFull()) {
showWinner('平局');
return;
}
// 切换到玩家回合
if (aiEnabled) {
currentPlayer = playerColor;
updateStatus();
}
}
// 检查是否为威胁位置(如三连子、四连子等)
function isThreateningMove(row, col, player) {
const directions = [
[0, 1], // 横向
[1, 0], // 纵向
[1, 1], // 左上到右下
[1, -1] // 右上到左下
];
for (const [dx, dy] of directions) {
let consecutive = 1;
let empty = 0;
let blocked = 0;
// 向一个方向检查
for (let i = 1; i <= 4; i++) {
const newRow = row + i * dx;
const newCol = col + i * dy;
if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
blocked++;
break;
}
if (board[newRow][newCol] === player) {
consecutive++;
} else if (board[newRow][newCol] === EMPTY) {
empty++;
break;
} else {
blocked++;
break;
}
}
// 向相反方向检查
for (let i = 1; i <= 4; i++) {
const newRow = row - i * dx;
const newCol = col - i * dy;
if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
blocked++;
break;
}
if (board[newRow][newCol] === player) {
consecutive++;
} else if (board[newRow][newCol] === EMPTY) {
empty++;
break;
} else {
blocked++;
break;
}
}
// 检查是否为威胁(四连子、活三连子、冲三连子)
if (consecutive >= 4) {
return true;
} else if (consecutive === 3 && (empty >= 1 && blocked === 0 || empty >= 1 && blocked === 1)) {
return true;
} else if (consecutive === 2 && empty >= 2 && blocked === 0) {
return true;
}
}
return false;
}
// 检查是否为活四
function isLiveFour(row, col, player) {
const directions = [
[0, 1], // 横向
[1, 0], // 纵向
[1, 1], // 左上到右下
[1, -1] // 右上到左下
];
for (const [dx, dy] of directions) {
let count = 1; // 当前位置的棋子
let leftEmpty = false;
let rightEmpty = false;
// 向一个方向检查(右/下)
let i = 1;
while (i <= 4) {
const newRow = row + i * dx;
const newCol = col + i * dy;
if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
break;
}
if (board[newRow][newCol] === player) {
count++;
} else if (board[newRow][newCol] === EMPTY) {
rightEmpty = true;
break;
} else {
break;
}
i++;
}
// 向相反方向检查(左/上)
i = 1;
while (i <= 4) {
const newRow = row - i * dx;
const newCol = col - i * dy;
if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
break;
}
if (board[newRow][newCol] === player) {
count++;
} else if (board[newRow][newCol] === EMPTY) {
leftEmpty = true;
break;
} else {
break;
}
i++;
}
// 活四:一条连续的4个子,两端都没有被对方棋子堵住,两边都能下子成五
if (count === 4 && leftEmpty && rightEmpty) {
return true;
}
}
return false;
}
// 检查是否为活三
function isLiveThree(row, col, player) {
const directions = [
[0, 1], // 横向
[1, 0], // 纵向
[1, 1], // 左上到右下
[1, -1] // 右上到左下
];
for (const [dx, dy] of directions) {
let count = 1; // 当前位置的棋子
let emptyPositions = [];
// 向一个方向检查
let i = 1;
while (i <= 4) {
const newRow = row + i * dx;
const newCol = col + i * dy;
if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
break;
}
if (board[newRow][newCol] === player) {
count++;
} else if (board[newRow][newCol] === EMPTY) {
emptyPositions.push({row: newRow, col: newCol});
break;
} else {
break;
}
i++;
}
// 向相反方向检查
i = 1;
while (i <= 4) {
const newRow = row - i * dx;
const newCol = col - i * dy;
if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
break;
}
if (board[newRow][newCol] === player) {
count++;
} else if (board[newRow][newCol] === EMPTY) {
emptyPositions.push({row: newRow, col: newCol});
break;
} else {
break;
}
i++;
}
// 活三:总共有3个同色棋子,并且至少有一个空位可以形成活四
if (count === 3) {
// 检查是否有任何空位可以形成活四
for (const pos of emptyPositions) {
// 临时在空位落子
board[pos.row][pos.col] = player;
const isLiveFourResult = isLiveFour(pos.row, pos.col, player);
board[pos.row][pos.col] = EMPTY;
if (isLiveFourResult) {
return true;
}
}
}
}
return false;
}
// 检查是否为双活三(三三禁手)
function hasDoubleLiveThree(row, col, player) {
let liveThreeCount = 0;
const directions = [
[0, 1], // 横向
[1, 0], // 纵向
[1, 1], // 左上到右下
[1, -1] // 右上到左下
];
// 检查当前落子在四个方向上是否形成活三
for (const [dx, dy] of directions) {
let count = 1; // 当前位置的棋子
let emptyPositions = [];
// 向一个方向检查
let i = 1;
while (i <= 4) {
const newRow = row + i * dx;
const newCol = col + i * dy;
if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
break;
}
if (board[newRow][newCol] === player) {
count++;
} else if (board[newRow][newCol] === EMPTY) {
emptyPositions.push({row: newRow, col: newCol});
break;
} else {
break;
}
i++;
}
// 向相反方向检查
i = 1;
while (i <= 4) {
const newRow = row - i * dx;
const newCol = col - i * dy;
if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
break;
}
if (board[newRow][newCol] === player) {
count++;
} else if (board[newRow][newCol] === EMPTY) {
emptyPositions.push({row: newRow, col: newCol});
break;
} else {
break;
}
i++;
}
// 检查是否形成活三
if (count === 3) {
// 检查是否有任何空位可以形成活四
for (const pos of emptyPositions) {
// 临时在空位落子
board[pos.row][pos.col] = player;
const isLiveFourResult = isLiveFour(pos.row, pos.col, player);
board[pos.row][pos.col] = EMPTY;
if (isLiveFourResult) {
liveThreeCount++;
break; // 每个方向只算一个活三
}
}
}
}
// 三三禁手:同时形成两个或以上的活三
return liveThreeCount >= 2;
}
// 检查是否为长连禁手(超过五连子)
function hasLongLine(row, col, player) {
const directions = [
[0, 1], // 横向
[1, 0], // 纵向
[1, 1], // 左上到右下
[1, -1] // 右上到左下
];
for (const [dx, dy] of directions) {
let consecutive = 1;
// 向一个方向检查
for (let i = 1; i <= 5; i++) {
const newRow = row + i * dx;
const newCol = col + i * dy;
if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
break;
}
if (board[newRow][newCol] === player) {
consecutive++;
} else {
break;
}
}
// 向相反方向检查
for (let i = 1; i <= 5; i++) {
const newRow = row - i * dx;
const newCol = col - i * dy;
if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
break;
}
if (board[newRow][newCol] === player) {
consecutive++;
} else {
break;
}
}
// 长连:超过五连子
if (consecutive > 5) {
return true;
}
}
return false;
}
// 检查是否为禁手
function isForbiddenMove(row, col, player) {
if (!forbiddenMovesEnabled || player !== BLACK) {
return false;
}
// 检查三三禁手
board[row][col] = player;
const hasTripleTriple = hasDoubleLiveThree(row, col, player);
// 检查四四禁手
const hasQuadrupleQuadruple = has44Combination(row, col, player);
// 检查长连禁手
const hasLong = hasLongLine(row, col, player);
board[row][col] = EMPTY;
return hasTripleTriple || hasQuadrupleQuadruple || hasLong;
}
// 切换黑子禁手模式
function toggleForbiddenMoves() {
const checkbox = document.getElementById('forbidden-moves');
forbiddenMovesEnabled = checkbox.checked;
}
// 切换AI启用状态
function toggleAI() {
const checkbox = document.getElementById('ai-enabled');
aiEnabled = checkbox.checked;
updateStatus();
}
// 显示规则
function showRules() {
document.getElementById('rules').style.display = 'flex';
}
// 隐藏规则
function hideRules() {
document.getElementById('rules').style.display = 'none';
}
// 评估威胁级别
function evaluateThreatLevel(row, col, player) {
const directions = [
[0, 1], // 横向
[1, 0], // 纵向
[1, 1], // 左上到右下
[1, -1] // 右上到左下
];
let maxThreatLevel = 0;
for (const [dx, dy] of directions) {
let consecutive = 1;
let empty = 0;
let blocked = 0;
// 向一个方向检查
for (let i = 1; i <= 4; i++) {
const newRow = row + i * dx;
const newCol = col + i * dy;
if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
blocked++;
break;
}
if (board[newRow][newCol] === player) {
consecutive++;
} else if (board[newRow][newCol] === EMPTY) {
empty++;
break;
} else {
blocked++;
break;
}
}
// 向相反方向检查
for (let i = 1; i <= 4; i++) {
const newRow = row - i * dx;
const newCol = col - i * dy;
if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
blocked++;
break;
}
if (board[newRow][newCol] === player) {
consecutive++;
} else if (board[newRow][newCol] === EMPTY) {
empty++;
break;
} else {
blocked++;
break;
}
}
// 评估威胁级别
let threatLevel = 0;
if (consecutive >= 5) {
threatLevel = 100000;
} else if (consecutive === 4 && empty >= 1 && blocked === 0) {
threatLevel = 10000;
} else if (consecutive === 4 && empty === 1 && blocked === 1) {
threatLevel = 5000;
} else if (consecutive === 3 && empty >= 2 && blocked === 0) {
threatLevel = 2000;
} else if (consecutive === 3 && (empty === 1 && blocked === 0 || empty === 2 && blocked === 1)) {
threatLevel = 1000;
} else if (consecutive === 2 && empty >= 2 && blocked === 0) {
threatLevel = 500;
}
if (threatLevel > maxThreatLevel) {
maxThreatLevel = threatLevel;
}
}
return maxThreatLevel;
}
// 检查是否为冲四(包括连四和跳四)
function isFourInARow(row, col, player) {
const directions = [
[0, 1], // 横向
[1, 0], // 纵向
[1, 1], // 左上到右下
[1, -1] // 右上到左下
];
for (const [dx, dy] of directions) {
let count = 1; // 当前位置的棋子
let hasEmpty = false;
let emptyPos = null;
// 向一个方向检查
let i = 1;
while (i <= 4) {
const newRow = row + i * dx;
const newCol = col + i * dy;
if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
break;
}
if (board[newRow][newCol] === player) {
count++;
} else if (board[newRow][newCol] === EMPTY) {
hasEmpty = true;
emptyPos = {row: newRow, col: newCol};
// 继续检查后面是否有同色棋子(跳四的情况)
let j = i + 1;
while (j <= 4) {
const nextRow = row + j * dx;
const nextCol = col + j * dy;
if (nextRow < 0 || nextRow >= BOARD_SIZE || nextCol < 0 || nextCol >= BOARD_SIZE) {
break;
}
if (board[nextRow][nextCol] === player) {
count++;
} else {
break;
}
j++;
}
break;
} else {
break;
}
i++;
}
// 向相反方向检查
i = 1;
while (i <= 4) {
const newRow = row - i * dx;
const newCol = col - i * dy;
if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
break;
}
if (board[newRow][newCol] === player) {
count++;
} else if (board[newRow][newCol] === EMPTY) {
hasEmpty = true;
emptyPos = {row: newRow, col: newCol};
// 继续检查后面是否有同色棋子(跳四的情况)
let j = i + 1;
while (j <= 4) {
const nextRow = row - j * dx;
const nextCol = col - j * dy;
if (nextRow < 0 || nextRow >= BOARD_SIZE || nextCol < 0 || nextCol >= BOARD_SIZE) {
break;
}
if (board[nextRow][nextCol] === player) {
count++;
} else {
break;
}
j++;
}
break;
} else {
break;
}
i++;
}
// 冲四:包括连四(4个连续)和跳四(OO.OO),只要能一步成五
if (count === 4) {
return true;
}
}
return false;
}
// 检查是否为34组合(活三+冲四)
function has34Combination(row, col, player) {
let hasLiveThree = false;
let hasFourInARow = false;
// 检查当前位置是否形成活三
board[row][col] = player;
if (isLiveThree(row, col, player)) {
hasLiveThree = true;
}
// 检查当前位置是否形成冲四
if (isFourInARow(row, col, player)) {
hasFourInARow = true;
}
board[row][col] = EMPTY;
return hasLiveThree && hasFourInARow;
}
// 检查是否为44组合(双冲四)
function has44Combination(row, col, player) {
let fourCount = 0;
board[row][col] = player;
// 检查四个方向是否有冲四
const directions = [
[0, 1], // 横向
[1, 0], // 纵向
[1, 1], // 左上到右下
[1, -1] // 右上到左下
];
for (const [dx, dy] of directions) {
let count = 1; // 当前位置的棋子
// 向一个方向检查
let i = 1;
while (i <= 4) {
const newRow = row + i * dx;
const newCol = col + i * dy;
if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
break;
}
if (board[newRow][newCol] === player) {
count++;
} else if (board[newRow][newCol] === EMPTY) {
// 继续检查后面是否有同色棋子(跳四的情况)
let j = i + 1;
while (j <= 4) {
const nextRow = row + j * dx;
const nextCol = col + j * dy;
if (nextRow < 0 || nextRow >= BOARD_SIZE || nextCol < 0 || nextCol >= BOARD_SIZE) {
break;
}
if (board[nextRow][nextCol] === player) {
count++;
} else {
break;
}
j++;
}
break;
} else {
break;
}
i++;
}
// 向相反方向检查
i = 1;
while (i <= 4) {
const newRow = row - i * dx;
const newCol = col - i * dy;
if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
break;
}
if (board[newRow][newCol] === player) {
count++;
} else if (board[newRow][newCol] === EMPTY) {
// 继续检查后面是否有同色棋子(跳四的情况)
let j = i + 1;
while (j <= 4) {
const nextRow = row - j * dx;
const nextCol = col - j * dy;
if (nextRow < 0 || nextRow >= BOARD_SIZE || nextCol < 0 || nextCol >= BOARD_SIZE) {
break;
}
if (board[nextRow][nextCol] === player) {
count++;
} else {
break;
}
j++;
}
break;
} else {
break;
}
i++;
}
// 冲四:包括连四(4个连续)和跳四(OO.OO),只要能一步成五
if (count === 4) {
fourCount++;
}
}
board[row][col] = EMPTY;
return fourCount >= 2;
}
// 找到最佳落子位置
function findBestMove() {
let bestScore = -Infinity;
let bestMove = {row: 7, col: 7}; // 默认从中心开始
// 生成可能的落子位置
const possibleMoves = getPossibleMoves();
// 扩展可能的落子位置,确保包含防守位置
const extendedMoves = new Set();
possibleMoves.forEach(move => extendedMoves.add(`${move.row},${move.col}`));
// 添加所有相邻的空位置,确保不遗漏防守位置
for (let i = 0; i < BOARD_SIZE; i++) {
for (let j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] !== EMPTY) {
// 检查周围的空位置
for (let di = -2; di <= 2; di++) {
for (let dj = -2; dj <= 2; dj++) {
const ni = i + di;
const nj = j + dj;
if (ni >= 0 && ni < BOARD_SIZE && nj >= 0 && nj < BOARD_SIZE && board[ni][nj] === EMPTY) {
extendedMoves.add(`${ni},${nj}`);
}
}
}
}
}
}
// 转换回数组
const allPossibleMoves = Array.from(extendedMoves).map(str => {
const [row, col] = str.split(',').map(Number);
return {row, col};
});
// 1. 优先检查自己是否能形成五连子
for (const move of allPossibleMoves) {
// 检查是否为禁手
if (isForbiddenMove(move.row, move.col, aiColor)) {
continue;
}
board[move.row][move.col] = aiColor;
if (checkWin(move.row, move.col, aiColor)) {
board[move.row][move.col] = EMPTY;
return move; // 必须下五连子
}
board[move.row][move.col] = EMPTY;
}
// 2. 检查自己是否能形成冲四
for (const move of allPossibleMoves) {
// 检查是否为禁手
if (isForbiddenMove(move.row, move.col, aiColor)) {
continue;
}
board[move.row][move.col] = aiColor;
if (isFourInARow(move.row, move.col, aiColor)) {
board[move.row][move.col] = EMPTY;
return move; // 优先下冲四
}
board[move.row][move.col] = EMPTY;
}
// 2.1 检查自己是否能形成34组合(活三+冲四)
for (const move of allPossibleMoves) {
// 检查是否为禁手
if (isForbiddenMove(move.row, move.col, aiColor)) {
continue;
}
if (has34Combination(move.row, move.col, aiColor)) {
return move; // 优先下34组合
}
}
// 2.2 检查自己是否能形成44组合(双冲四)
for (const move of allPossibleMoves) {
// 检查是否为禁手
if (isForbiddenMove(move.row, move.col, aiColor)) {
continue;
}
if (has44Combination(move.row, move.col, aiColor)) {
return move; // 优先下44组合
}
}
// 3. 检查玩家是否能形成五连子
for (const move of allPossibleMoves) {
board[move.row][move.col] = playerColor;
if (checkWin(move.row, move.col, playerColor)) {
board[move.row][move.col] = EMPTY;
return move; // 必须防守五连子
}
board[move.row][move.col] = EMPTY;
}
// 4. 检查玩家是否能形成冲四
for (const move of allPossibleMoves) {
board[move.row][move.col] = playerColor;
if (isFourInARow(move.row, move.col, playerColor)) {
board[move.row][move.col] = EMPTY;
return move; // 必须防守冲四
}
board[move.row][move.col] = EMPTY;
}
// 5. 优先检查玩家的其他威胁
let highestThreatMove = null;
let highestThreatLevel = 0;
for (const move of allPossibleMoves) {
// 评估威胁级别
board[move.row][move.col] = playerColor;
const threatLevel = evaluateThreatLevel(move.row, move.col, playerColor);
board[move.row][move.col] = EMPTY;
if (threatLevel > highestThreatLevel) {
highestThreatLevel = threatLevel;
highestThreatMove = move;
}
}
// 6. 如果有严重威胁,优先防守
if (highestThreatLevel > 1000) {
return highestThreatMove;
}
// 7. 检查对手是否有双活三
// 遍历所有空位置,检查是否有双活三的可能
let hasDoubleThree = false;
for (const move of allPossibleMoves) {
board[move.row][move.col] = playerColor;
if (hasDoubleLiveThree(move.row, move.col, playerColor)) {
hasDoubleThree = true;
board[move.row][move.col] = EMPTY;
break;
}
board[move.row][move.col] = EMPTY;
}
if (hasDoubleThree) {
// 寻找冲四的位置
for (const move of allPossibleMoves) {
board[move.row][move.col] = aiColor;
if (isFourInARow(move.row, move.col, aiColor)) {
board[move.row][move.col] = EMPTY;
return move; // 下冲四应对双活三
}
board[move.row][move.col] = EMPTY;
}
}
// 8. 限制搜索节点数量,提高性能
const limitedMoves = allPossibleMoves.slice(0, 20);
for (const move of limitedMoves) {
// 检查是否为禁手
if (isForbiddenMove(move.row, move.col, aiColor)) {
continue;
}
board[move.row][move.col] = aiColor;
const score = minimax(4, -Infinity, Infinity, false);
board[move.row][move.col] = EMPTY;
if (score > bestScore) {
bestScore = score;
bestMove = move;
}
}
return bestMove;
}
// 生成可能的落子位置
function getPossibleMoves() {
const moves = [];
// 只考虑有相邻棋子的位置
for (let i = 0; i < BOARD_SIZE; i++) {
for (let j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] === EMPTY && hasAdjacentPieces(i, j)) {
moves.push({row: i, col: j});
}
}
}
// 如果没有相邻棋子,从中心开始
if (moves.length === 0) {
moves.push({row: 7, col: 7});
}
// 按评分排序,优先考虑重要位置
moves.sort((a, b) => {
const scoreA = evaluatePosition(a.row, a.col, aiColor);
const scoreB = evaluatePosition(b.row, b.col, aiColor);
return scoreB - scoreA;
});
// 只考虑前20个最佳位置,提高性能
return moves.slice(0, 20);
}
// 检查是否有相邻棋子
function hasAdjacentPieces(row, col) {
for (let i = Math.max(0, row - 2); i <= Math.min(BOARD_SIZE - 1, row + 2); i++) {
for (let j = Math.max(0, col - 2); j <= Math.min(BOARD_SIZE - 1, col + 2); j++) {
if (board[i][j] !== EMPTY) {
return true;
}
}
}
return false;
}
// 极大极小算法
function minimax(depth, alpha, beta, isMaximizing) {
// 检查终止条件
if (depth === 0) {
return evaluateBoard();
}
if (isMaximizing) {
let maxScore = -Infinity;
const possibleMoves = getPossibleMoves();
for (const move of possibleMoves) {
// 检查是否为禁手
if (isForbiddenMove(move.row, move.col, aiColor)) {
continue;
}
board[move.row][move.col] = aiColor;
// 检查是否获胜
if (checkWin(move.row, move.col, aiColor)) {
board[move.row][move.col] = EMPTY;
return 10000 + depth; // 获胜加分,深度越大分越高
}
const score = minimax(depth - 1, alpha, beta, false);
board[move.row][move.col] = EMPTY;
maxScore = Math.max(maxScore, score);
alpha = Math.max(alpha, score);
if (beta <= alpha) {
break; // alpha-beta剪枝
}
}
return maxScore;
} else {
let minScore = Infinity;
const possibleMoves = getPossibleMoves();
for (const move of possibleMoves) {
board[move.row][move.col] = playerColor;
// 检查是否获胜
if (checkWin(move.row, move.col, playerColor)) {
board[move.row][move.col] = EMPTY;
return -10000 - depth; // 对手获胜减分,深度越大分越低
}
const score = minimax(depth - 1, alpha, beta, true);
board[move.row][move.col] = EMPTY;
minScore = Math.min(minScore, score);
beta = Math.min(beta, score);
if (beta <= alpha) {
break; // alpha-beta剪枝
}
}
return minScore;
}
}
// 评估棋盘
function evaluateBoard() {
let score = 0;
// 评估每个位置
for (let i = 0; i < BOARD_SIZE; i++) {
for (let j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] === aiColor) {
score += evaluatePosition(i, j, aiColor);
} else if (board[i][j] === playerColor) {
score -= evaluatePosition(i, j, playerColor);
}
}
}
return score;
}
// 评估位置
function evaluatePosition(row, col, player) {
const directions = [
[0, 1], // 横向
[1, 0], // 纵向
[1, 1], // 左上到右下
[1, -1] // 右上到左下
];
let totalScore = 0;
for (const [dx, dy] of directions) {
let consecutive = 1;
let empty = 0;
let blocked = 0;
// 向一个方向检查
for (let i = 1; i <= 4; i++) {
const newRow = row + i * dx;
const newCol = col + i * dy;
if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
blocked++;
break;
}
if (board[newRow][newCol] === player) {
consecutive++;
} else if (board[newRow][newCol] === EMPTY) {
empty++;
break;
} else {
blocked++;
break;
}
}
// 向相反方向检查
for (let i = 1; i <= 4; i++) {
const newRow = row - i * dx;
const newCol = col - i * dy;
if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
blocked++;
break;
}
if (board[newRow][newCol] === player) {
consecutive++;
} else if (board[newRow][newCol] === EMPTY) {
empty++;
break;
} else {
blocked++;
break;
}
}
// 根据连续棋子数和阻塞情况计算分数
totalScore += calculateScore(consecutive, empty, blocked);
}
return totalScore;
}
// 计算分数
function calculateScore(consecutive, empty, blocked) {
if (consecutive >= 5) {
return 100000; // 五连子
} else if (consecutive === 4 && empty >= 1 && blocked === 0) {
return 10000; // 活四
} else if (consecutive === 4 && empty === 1 && blocked === 1) {
return 5000; // 冲四
} else if (consecutive === 3 && empty >= 2 && blocked === 0) {
return 2000; // 活三
} else if (consecutive === 3 && (empty === 1 && blocked === 0 || empty === 2 && blocked === 1)) {
return 1000; // 冲三
} else if (consecutive === 2 && empty >= 2 && blocked === 0) {
return 500; // 活二
} else if (consecutive === 2 && (empty === 1 && blocked === 0 || empty === 2 && blocked === 1)) {
return 200; // 冲二
} else if (consecutive === 1 && empty >= 2 && blocked === 0) {
return 100; // 活一
}
return 0;
}
// 导出棋局
function exportGame() {
// 自定义64进制字符集(使用URL安全的字符)
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
// 将棋盘划分为5x5个3x3的块
const BLOCK_SIZE = 3;
const BLOCKS_PER_SIDE = BOARD_SIZE / BLOCK_SIZE; // 5
// 编码每个块
let encoded = '';
for (let blockRow = 0; blockRow < BLOCKS_PER_SIDE; blockRow++) {
for (let blockCol = 0; blockCol < BLOCKS_PER_SIDE; blockCol++) {
// 计算块的状态
let blockState = 0;
let hasPiece = false;
for (let i = 0; i < BLOCK_SIZE; i++) {
for (let j = 0; j < BLOCK_SIZE; j++) {
const row = blockRow * BLOCK_SIZE + i;
const col = blockCol * BLOCK_SIZE + j;
const cellValue = board[row][col];
if (cellValue !== EMPTY) {
hasPiece = true;
}
// 每个位置用2位表示
blockState = (blockState << 2) | cellValue;
}
}
// 只编码有棋子的块
if (hasPiece) {
// 块位置编码 (blockRow * 5 + blockCol)
const blockPos = blockRow * BLOCKS_PER_SIDE + blockCol;
// 总编码:块位置(5位) + 块状态(18位) = 23位
const totalCode = (blockPos << 18) | blockState;
// 转换为4位64进制
encoded += chars[totalCode >> 18 & 0x3F];
encoded += chars[totalCode >> 12 & 0x3F];
encoded += chars[totalCode >> 6 & 0x3F];
encoded += chars[totalCode & 0x3F];
}
}
}
// 添加结束标记
encoded += '~';
// 添加额外信息(12位)
let extra = (currentPlayer << 8) |
(playerColor << 6) |
(aiColor << 4) |
(forbiddenMovesEnabled ? 1 << 1 : 0) |
(gameOver ? 1 : 0);
encoded += chars[extra >> 6 & 0x3F];
encoded += chars[extra & 0x3F];
// 复制到剪贴板
navigator.clipboard.writeText(encoded).then(() => {
alert('棋局已导出并复制到剪贴板!');
}).catch(err => {
console.error('复制失败:', err);
// 如果复制失败,显示字符串
const input = document.getElementById('import-input');
input.value = encoded;
alert('棋局已导出,请手动复制输入框中的字符串!');
});
}
// 导入棋局
function importGame() {
const input = document.getElementById('import-input');
const gameString = input.value.trim();
if (!gameString) {
alert('请输入棋局字符串!');
return;
}
try {
// 自定义64进制字符集(使用URL安全的字符)
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
// 重置棋盘
for (let i = 0; i < BOARD_SIZE; i++) {
for (let j = 0; j < BOARD_SIZE; j++) {
board[i][j] = EMPTY;
}
}
// 解析块编码
let i = 0;
const BLOCK_SIZE = 3;
const BLOCKS_PER_SIDE = BOARD_SIZE / BLOCK_SIZE; // 5
while (i < gameString.length) {
// 找到结束标记
if (gameString[i] === '~') {
i++;
break;
}
// 每4个字符表示一个块
if (i + 3 >= gameString.length) break;
const c1 = chars.indexOf(gameString[i]);
const c2 = chars.indexOf(gameString[i+1]);
const c3 = chars.indexOf(gameString[i+2]);
const c4 = chars.indexOf(gameString[i+3]);
if (c1 === -1 || c2 === -1 || c3 === -1 || c4 === -1) {
throw new Error('Invalid character');
}
const totalCode = (c1 << 18) | (c2 << 12) | (c3 << 6) | c4;
const blockPos = totalCode >> 18;
const blockState = totalCode & 0x3FFFF; // 18位
// 计算块的位置
const blockRow = Math.floor(blockPos / BLOCKS_PER_SIDE);
const blockCol = blockPos % BLOCKS_PER_SIDE;
// 解析块状态
let state = blockState;
for (let rowOffset = BLOCK_SIZE - 1; rowOffset >= 0; rowOffset--) {
for (let colOffset = BLOCK_SIZE - 1; colOffset >= 0; colOffset--) {
const value = state & 3;
const row = blockRow * BLOCK_SIZE + rowOffset;
const col = blockCol * BLOCK_SIZE + colOffset;
if (row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE) {
board[row][col] = value;
}
state >>= 2;
}
}
i += 4;
}
// 解析额外信息
if (i + 1 < gameString.length) {
const c1 = chars.indexOf(gameString[i]);
const c2 = chars.indexOf(gameString[i+1]);
if (c1 === -1 || c2 === -1) {
throw new Error('Invalid character');
}
const extra = (c1 << 6) | c2;
currentPlayer = (extra >> 8) & 3;
playerColor = (extra >> 6) & 3;
aiColor = (extra >> 4) & 3;
forbiddenMovesEnabled = ((extra >> 1) & 1) === 1;
gameOver = (extra & 1) === 1;
document.getElementById('forbidden-moves').checked = forbiddenMovesEnabled;
// 更新选择颜色的显示
const selectedColorElement = document.getElementById('selected-color');
selectedColorElement.textContent = `已选择:${playerColor === BLACK ? '黑棋' : '白棋'}`;
}
// 重新初始化棋盘
initBoard();
// 重新绘制棋子
for (let i = 0; i < BOARD_SIZE; i++) {
for (let j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] !== EMPTY) {
const cell = document.querySelector(`[data-row="${i}"][data-col="${j}"]`);
const piece = document.createElement('div');
piece.classList.add('piece');
piece.classList.add(board[i][j] === BLACK ? 'black' : 'white');
cell.appendChild(piece);
}
}
}
// 更新状态
updateStatus();
// 隐藏获胜界面
document.getElementById('winner').style.display = 'none';
alert('棋局导入成功!');
} catch (error) {
console.error('导入失败:', error);
alert('棋局字符串格式错误!');
}
}
// 初始化游戏
initBoard();
// 确保难度显示为困难
document.getElementById('difficulty-value').textContent = '困难';
</script>
</body>
</html>
:::: 本篇文章中的代码和介绍均由AI生成