横评报告大模型
同题横评:用 HTML + 原生 JavaScript(不使用任何外部…
AI 大众点评·…
结论速览
本报告由「AI 大众点评 · 同题横评工作台」自动生成,同一任务并发调用多家大模型后对比输出。
本次横评产品(4)
# 同题横评# DeepSeek# 通义千问# Kimi# 智谱 GLM
横评任务
用 HTML + 原生 JavaScript(不使用任何外部依赖、不引用任何 CDN)生成一个完整、可直接在浏览器打开运行的单文件中国象棋游戏。要求:①绘制标准 9×10 棋盘与河界、九宫格;②实现全部棋子的走子规则(车马炮相仕帅兵卒),含马蹩腿、象塞眼、炮翻山、将帅照面、不能自吃、不能送将;③鼠标点击选中与移动,红黑双方轮流走子;④内置简单 AI,支持人机对战;⑤有“重新开始”按钮与“当前轮到谁”的提示。只输出完整 HTML 代码,用 ```html 代码块包裹,不要任何解释文字、不要分步说明。
综合排名
冠军DeepSeek8.2综合分 / 10
亚军通义千问7.7综合分 / 10
季军智谱 GLM3.9综合分 / 10
第 4 名Kimi3.8综合分 / 10
指标对比
| DeepSeek冠军 | 通义千问亚军 | 智谱 GLM季军 | Kimi | |
|---|---|---|---|---|
| 综合分 | 8.2 | 7.7 | 3.9 | 3.8 |
| 质量分 | 8.8 | 8.8 | 2.6 | 4.5 |
| 性能分 | 6.8 | 5.1 | 6.8 | 2.0 |
| 正确性/可运行性 | 9.0 | 9.0 | 1.0 | 3.0 |
| 逻辑性 | 8.5 | 8.5 | 2.5 | 4.0 |
| 完整性 | 10.0 | 10.0 | 3.3 | 5.8 |
| 稳定性 | 8.0 | 8.0 | 2.0 | 5.0 |
| 风格 | 8.0 | 8.0 | 5.0 | 6.0 |
| 效率 | 7.0 | 7.0 | 7.0 | 7.0 |
| 响应耗时 | 30.6s | 157.0s | 157.8s | 208.9s |
| Token(入/出) | 166 / 7884 | 185 / 7100 | 172 / 3201 | 164 / 8192 |
| 调用费用(估算) | ¥0.02 | ¥0.01 | 免费 | ¥0.13 |
| 单位产出成本 | ¥0.0024 / 分 | ¥0.0013 / 分 | 翻车·不计 | 截断·不计 |
高亮为该指标最优值。综合分 = 质量 × 70% + 性能 × 30%;性能分 = 速度 45% + Token 40% + 费用 15%;质量分六维加权(可运行性 30 / 逻辑 25 / 完整 20 / 稳定 10 / 风格 10 / 效率 5)。输出被截断或可运行性 ≤ 2 时,综合分封顶 4.0。
调用费用按各模型官方刊例价 × 真实 token 用量折算,仅为平台 API 成本估算,用户使用横评无需付费。「单位产出成本」= 调用费用 ÷ 综合分(每得 1 分的成本,越低越划算),截断或可运行性 ≤ 2 的样本标注「不计」,不参与最优比较。
输出对比
左右滑动查看各家产物,可直接在线试玩
点击放大试玩
查看完整源码
```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>
* {
box-sizing: border-box;
user-select: none;
}
body {
min-height: 100vh;
margin: 0;
background: linear-gradient(145deg, #3f2b1e, #2a1e14);
display: flex;
justify-content: center;
align-items: center;
font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
}
.game-container {
background: #d9b382;
padding: 2rem 2.5rem 2.5rem 2.5rem;
border-radius: 3rem 3rem 2rem 2rem;
box-shadow: 0 25px 30px rgba(0, 0, 0, 0.7), inset 0 0 8px #f7e9d7;
border-bottom: 8px solid #b2824e;
}
canvas {
display: block;
margin: 0 auto;
background: #f3e3c9;
border-radius: 18px;
box-shadow: 0 0 0 2px #8b6b45, 0 20px 25px rgba(0, 0, 0, 0.5);
cursor: pointer;
}
.info-panel {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 1.8rem;
padding: 0 0.5rem;
color: #1f140e;
font-weight: bold;
font-size: 1.3rem;
text-shadow: 1px 1px 0 #e9d6ba;
}
.turn-indicator {
background: #2e2118;
color: #f3d9b1;
padding: 0.5rem 1.6rem;
border-radius: 3rem;
box-shadow: inset 0 -3px 0 #0f0a07, 0 6px 0 #0f0a07;
letter-spacing: 1px;
font-size: 1.2rem;
border: 1px solid #b99a75;
}
.restart-btn {
background: #b33e2c;
border: none;
color: #ffeac2;
font-weight: bold;
font-size: 1.2rem;
padding: 0.5rem 2rem;
border-radius: 3rem;
box-shadow: inset 0 -3px 0 #6f2319, 0 6px 0 #4d1810;
cursor: pointer;
transition: all 0.07s ease;
letter-spacing: 2px;
font-family: inherit;
border: 1px solid #d98f73;
}
.restart-btn:active {
transform: translateY(4px);
box-shadow: inset 0 -1px 0 #6f2319, 0 2px 0 #4d1810;
}
</style>
</head>
<body>
<div class="game-container">
<canvas id="chessCanvas" width="540" height="600"></canvas>
<div class="info-panel">
<div class="turn-indicator" id="turnText">红方走棋</div>
<button class="restart-btn" id="restartBtn">重新开始</button>
</div>
</div>
<script>
(function() {
// ---------- 常量与全局状态 ----------
const canvas = document.getElementById('chessCanvas');
const ctx = canvas.getContext('2d');
const turnText = document.getElementById('turnText');
// 棋盘尺寸(网格)
const COLS = 9; // 0~8
const ROWS = 10; // 0~9
const CELL_SIZE = 60; // 像素
const MARGIN_X = 30; // 左边距
const MARGIN_Y = 30; // 上边距
const BOARD_W = (COLS - 1) * CELL_SIZE; // 480
const BOARD_H = (ROWS - 1) * CELL_SIZE; // 540
// 棋子类型 (大写红方,小写黑方)
const RED = true;
const BLACK = false;
// 初始棋盘布局 (9列 x 10行)
const INIT_BOARD = [
// row 0 (黑方底线)
['r', 'n', 'b', 'a', 'k', 'a', 'b', 'n', 'r'],
// row 1 空
[null, null, null, null, null, null, null, null, null],
// row 2 空
[null, null, null, null, null, null, null, null, null],
// row 3 黑卒
[null, 'p', null, null, null, null, null, 'p', null],
// row 4 空
[null, null, null, null, null, null, null, null, null],
// row 5 空 (河界)
[null, null, null, null, null, null, null, null, null],
// row 6 红兵
[null, 'P', null, null, null, null, null, 'P', null],
// row 7 空
[null, null, null, null, null, null, null, null, null],
// row 8 空
[null, null, null, null, null, null, null, null, null],
// row 9 红方底线
['R', 'N', 'B', 'A', 'K', 'A', 'B', 'N', 'R']
];
// 棋子名称映射 (红方大写)
const PIECE_NAMES = {
'k': '将', 'a': '士', 'b': '象', 'n': '马', 'r': '车', 'c': '炮', 'p': '卒',
'K': '帅', 'A': '仕', 'B': '相', 'N': '马', 'R': '车', 'C': '炮', 'P': '兵'
};
// 当前游戏状态
let board = []; // 二维数组 10行 x 9列
let currentPlayer = RED; // true: 红方, false: 黑方
let selected = null; // { row, col } 或 null
let gameOver = false;
let waitingForAI = false; // 防止连续触发
// ---------- 工具函数 ----------
function cloneBoard(b) {
return b.map(row => row.slice());
}
// 判断坐标是否在棋盘内
function inside(row, col) {
return row >= 0 && row < ROWS && col >= 0 && col < COLS;
}
// 判断是否红方棋子 (大写)
function isRed(piece) {
return piece && piece === piece.toUpperCase();
}
// 判断是否黑方棋子
function isBlack(piece) {
return piece && piece === piece.toLowerCase();
}
// 获取某方所有棋子位置
function getPiecesByColor(board, red) {
const res = [];
for (let r = 0; r < ROWS; r++) {
for (let c = 0; c < COLS; c++) {
const p = board[r][c];
if (!p) continue;
if (red && isRed(p)) res.push({ row: r, col: c });
else if (!red && isBlack(p)) res.push({ row: r, col: c });
}
}
return res;
}
// 找到将/帅位置
function findKing(board, red) {
const kingChar = red ? 'K' : 'k';
for (let r = 0; r < ROWS; r++) {
for (let c = 0; c < COLS; c++) {
if (board[r][c] === kingChar) return { row: r, col: c };
}
}
return null; // 理论上不会发生
}
// ---------- 核心规则: 生成某棋子的合法移动(不含送将检查) ----------
function getRawMoves(board, row, col) {
const piece = board[row][col];
if (!piece) return [];
const red = isRed(piece);
const type = piece.toUpperCase(); // 'K','A','B','N','R','C','P'
const moves = [];
// 辅助函数: 检查目标位置是否可去 (不能吃己方棋子)
function canPlace(tr, tc) {
if (!inside(tr, tc)) return false;
const target = board[tr][tc];
if (!target) return true; // 空位
return isRed(target) !== red; // 不同颜色才能吃
}
// 根据类型生成
if (type === 'R') { // 车
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
for (let [dr, dc] of dirs) {
for (let step = 1; ; step++) {
const nr = row + dr * step, nc = col + dc * step;
if (!inside(nr, nc)) break;
const target = board[nr][nc];
if (!target) {
moves.push({ row: nr, col: nc });
} else {
if (isRed(target) !== red) moves.push({ row: nr, col: nc });
break; // 遇到棋子停止
}
}
}
} else if (type === 'N') { // 马
const horseJumps = [
[-2, -1], [-2, 1], [-1, -2], [-1, 2],
[1, -2], [1, 2], [2, -1], [2, 1]
];
for (let [dr, dc] of horseJumps) {
const nr = row + dr, nc = col + dc;
if (!canPlace(nr, nc)) continue;
// 蹩腿: 检查马腿位置 (row + dr/2 等)
let legRow, legCol;
if (Math.abs(dr) === 2) {
legRow = row + (dr > 0 ? 1 : -1);
legCol = col;
} else {
legRow = row;
legCol = col + (dc > 0 ? 1 : -1);
}
if (board[legRow][legCol] === null) { // 马腿无棋子
moves.push({ row: nr, col: nc });
}
}
} else if (type === 'B') { // 象/相
const elephantDirs = [[2, 2], [2, -2], [-2, 2], [-2, -2]];
for (let [dr, dc] of elephantDirs) {
const nr = row + dr, nc = col + dc;
if (!canPlace(nr, nc)) continue;
// 塞象眼
const eyeRow = row + dr / 2;
const eyeCol = col + dc / 2;
if (board[eyeRow][eyeCol] !== null) continue;
// 不能过河: 红方row>=5,黑方row<=4
if (red && nr < 5) continue;
if (!red && nr > 4) continue;
moves.push({ row: nr, col: nc });
}
} else if (type === 'A') { // 士/仕
const advisorDirs = [[1, 1], [1, -1], [-1, 1], [-1, -1]];
for (let [dr, dc] of advisorDirs) {
const nr = row + dr, nc = col + dc;
if (!canPlace(nr, nc)) continue;
// 九宫范围: 红方 row 7-9, col 3-5; 黑方 row 0-2, col 3-5
if (red) {
if (nr < 7 || nr > 9 || nc < 3 || nc > 5) continue;
} else {
if (nr < 0 || nr > 2 || nc < 3 || nc > 5) continue;
}
moves.push({ row: nr, col: nc });
}
} else if (type === 'K') { // 将/帅
const kingDirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
for (let [dr, dc] of kingDirs) {
const nr = row + dr, nc = col + dc;
if (!canPlace(nr, nc)) continue;
// 九宫
if (red) {
if (nr < 7 || nr > 9 || nc < 3 || nc > 5) continue;
} else {
if (nr < 0 || nr > 2 || nc < 3 || nc > 5) continue;
}
moves.push({ row: nr, col: nc });
}
// 特殊: 将帅照面 (飞将) 会在后续"isKingFace"中拦截,但这里也要生成对方的将作为合法走法?
// 但正常走子不能直接将移动到对方将位置(除非照面吃将)。规则上"飞将"是指不能主动造成照面,
// 这里简单生成对脸位置的移动(吃对方将),但实际对局中极少直接吃将,我们通过送将检查来过滤。
// 为了处理"飞将吃将"的合法性,如果对方将和己方将同一列且中间无棋子,则可以移动到对方将位置。
// 但是否应该允许直接吃将? 中国象棋中不能主动照面,但是将吃将只发生在照面时,而照面本身非法(对方送将)。
// 所以这里不额外生成,保留常规移动。照面检测由送将检查处理。
} else if (type === 'C') { // 炮
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
for (let [dr, dc] of dirs) {
let step = 1;
let hasJumped = false;
while (true) {
const nr = row + dr * step, nc = col + dc * step;
if (!inside(nr, nc)) break;
const target = board[nr][nc];
if (!hasJumped) {
if (target === null) {
moves.push({ row: nr, col: nc });
} else {
hasJumped = true; // 遇到炮架
}
} else {
if (target !== null) {
if (isRed(target) !== red) moves.push({ row: nr, col: nc });
break; // 找到目标或己方棋子后停止
}
}
step++;
}
}
} else if (type === 'P') { // 兵/卒
// 红兵向上(row减小),黑卒向下(row增大)
const forward = red ? -1 : 1;
// 前进
if (canPlace(row + forward, col)) moves.push({ row: row + forward, col });
// 过河后可以左右移动 (红方 row <=4, 黑方 row >=5)
if (red && row <= 4 || !red && row >= 5) {
if (canPlace(row, col - 1)) moves.push({ row: row, col: col - 1 });
if (canPlace(row, col + 1)) moves.push({ row: row, col: col + 1 });
}
}
return moves;
}
// ---------- 将帅照面检查 ----------
function isKingFace(board, redTurn) {
const redKing = findKing(board, true);
const blackKing = findKing(board, false);
if (!redKing || !blackKing) return false;
if (redKing.col !== blackKing.col) return false;
// 检查中间是否有棋子
const minRow = Math.min(redKing.row, blackKing.row);
const maxRow = Math.max(redKing.row, blackKing.row);
for (let r = minRow + 1; r < maxRow; r++) {
if (board[r][redKing.col] !== null) return false;
}
// 没有棋子,将帅照面
return true;
}
// ---------- 检查某方是否被将军 (即走子后己方将帅被攻击 或 将帅照面) ----------
function isKingInCheck(board, red) {
const kingPos = findKing(board, red);
if (!kingPos) return true; // 将帅不存在(被吃) 视为被将军/游戏结束
const opponentRed = !red;
// 1. 检查将帅照面 (主动照面算被将军)
if (isKingFace(board, red)) return true;
// 2. 检查是否被对方棋子攻击
const oppPieces = getPiecesByColor(board, opponentRed);
for (let { row, col } of oppPieces) {
const moves = getRawMoves(board, row, col);
for (let m of moves) {
if (m.row === kingPos.row && m.col === kingPos.col) {
return true;
}
}
}
return false;
}
// ---------- 生成某方所有合法走法 (不送将) ----------
function generateLegalMoves(board, red) {
const legalMoves = [];
const pieces = getPiecesByColor(board, red);
for (let { row, col } of pieces) {
const rawMoves = getRawMoves(board, row, col);
for (let move of rawMoves) {
// 模拟移动
const newBoard = cloneBoard(board);
newBoard[move.row][move.col] = newBoard[row][col];
newBoard[row][col] = null;
// 检查己方将帅是否安全
if (!isKingInCheck(newBoard, red)) {
legalMoves.push({ from: { row, col }, to: { row: move.row, col: move.col } });
}
}
}
return legalMoves;
}
// ---------- 判断游戏结束 (当前玩家无合法走法 或 将帅被吃) ----------
function checkGameOver() {
// 检查将帅是否还在
const redKing = findKing(board, true);
const blackKing = findKing(board, false);
if (!redKing) {
gameOver = true;
turnText.innerText = '黑方胜!';
return true;
}
if (!blackKing) {
gameOver = true;
turnText.innerText = '红方胜!';
return true;
}
// 检查当前玩家是否有合法走法
const legal = generateLegalMoves(board, currentPlayer);
if (legal.length === 0) {
gameOver = true;
// 红方无棋可走则黑胜,反之亦然
turnText.innerText = currentPlayer ? '黑方胜!' : '红方胜!';
return true;
}
// 检查是否被将军(但仍有解) - 可以提示,但简化不额外处理
return false;
}
// ---------- 执行移动 (不检查合法性,调用前确保合法) ----------
function applyMove(board, from, to) {
board[to.row][to.col] = board[from.row][from.col];
board[from.row][from.col] = null;
}
// ---------- 切换玩家并更新状态 ----------
function switchPlayer() {
currentPlayer = !currentPlayer;
selected = null;
if (!gameOver) {
turnText.innerText = currentPlayer ? '红方走棋' : '黑方走棋';
}
}
// ---------- 绘制棋盘 (静态) ----------
function drawBoard() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 背景色
ctx.fillStyle = '#f3e3c9';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制网格线
ctx.lineWidth = 1.5;
ctx.strokeStyle = '#5d3f1f';
// 竖线 (9条)
for (let c = 0; c < COLS; c++) {
const x = MARGIN_X + c * CELL_SIZE;
if (c === 0 || c === COLS - 1) {
// 左右边线贯穿
ctx.beginPath();
ctx.moveTo(x, MARGIN_Y);
ctx.lineTo(x, MARGIN_Y + BOARD_H);
ctx.stroke();
} else {
// 中间竖线在河界处断开 (楚河汉界)
ctx.beginPath();
ctx.moveTo(x, MARGIN_Y);
ctx.lineTo(x, MARGIN_Y + 4 * CELL_SIZE); // 上半段
ctx.stroke();
ctx.beginPath();
ctx.moveTo(x, MARGIN_Y + 5 * CELL_SIZE); // 下半段
ctx.lineTo(x, MARGIN_Y + BOARD_H);
ctx.stroke();
}
}
// 横线 (10条)
for (let r = 0; r < ROWS; r++) {
const y = MARGIN_Y + r * CELL_SIZE;
ctx.beginPath();
ctx.moveTo(MARGIN_X, y);
ctx.lineTo(MARGIN_X + BOARD_W, y);
ctx.stroke();
}
// 绘制九宫斜线
ctx.beginPath();
// 黑方九宫 (row 0-2, col 3-5)
ctx.moveTo(MARGIN_X + 3 * CELL_SIZE, MARGIN_Y + 0 * CELL_SIZE);
ctx.lineTo(MARGIN_X + 5 * CELL_SIZE, MARGIN_Y + 2 * CELL_SIZE);
ctx.moveTo(MARGIN_X + 5 * CELL_SIZE, MARGIN_Y + 0 * CELL_SIZE);
ctx.lineTo(MARGIN_X + 3 * CELL_SIZE, MARGIN_Y + 2 * CELL_SIZE);
// 红方九宫 (row 7-9, col 3-5)
ctx.moveTo(MARGIN_X + 3 * CELL_SIZE, MARGIN_Y + 7 * CELL_SIZE);
ctx.lineTo(MARGIN_X + 5 * CELL_SIZE, MARGIN_Y + 9 * CELL_SIZE);
ctx.moveTo(MARGIN_X + 5 * CELL_SIZE, MARGIN_Y + 7 * CELL_SIZE);
ctx.lineTo(MARGIN_X + 3 * CELL_SIZE, MARGIN_Y + 9 * CELL_SIZE);
ctx.stroke();
// 绘制"楚河汉界"文字
ctx.font = 'bold 22px "KaiTi", "楷体", "Microsoft YaHei", sans-serif';
ctx.fillStyle = '#7a5d3c';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
const riverY = MARGIN_Y + 4.5 * CELL_SIZE;
ctx.fillText('楚 河', MARGIN_X + 1.8 * CELL_SIZE, riverY);
ctx.fillText('汉 界', MARGIN_X + 7.2 * CELL_SIZE, riverY);
// 绘制炮兵位标记 (可选) 小十字
// 此处省略,保持简洁
}
// ---------- 绘制棋子 ----------
function drawPiece(row, col, piece, isSelected) {
if (!piece) return;
const x = MARGIN_X + col * CELL_SIZE;
const y = MARGIN_Y + row * CELL_SIZE;
const radius = CELL_SIZE * 0.42;
const red = isRed(piece);
// 阴影
ctx.shadowColor = 'rgba(0, 0, 0, 0.3)';
ctx.shadowBlur = 8;
ctx.shadowOffsetX = 2;
ctx.shadowOffsetY = 2;
// 棋子底色
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.fillStyle = red ? '#f7e2c1' : '#e6d6b8';
ctx.fill();
ctx.shadowColor = 'transparent';
ctx.shadowBlur = 0;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
// 描边
ctx.lineWidth = 2.5;
ctx.strokeStyle = red ? '#b22222' : '#1e1e1e';
ctx.stroke();
// 内圈装饰
ctx.beginPath();
ctx.arc(x, y, radius * 0.75, 0, 2 * Math.PI);
ctx.strokeStyle = red ? '#b22222' : '#1e1e1e';
ctx.lineWidth = 1.5;
ctx.stroke();
// 文字
ctx.font = `bold ${CELL_SIZE * 0.55}px "KaiTi", "楷体", "Microsoft YaHei", sans-serif`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = red ? '#b22222' : '#1e1e1e';
ctx.fillText(PIECE_NAMES[piece], x, y + 2);
// 选中高亮
if (isSelected) {
ctx.beginPath();
ctx.arc(x, y, radius + 3, 0, 2 * Math.PI);
ctx.strokeStyle = '#f7d44a';
ctx.lineWidth = 4;
ctx.stroke();
ctx.beginPath();
ctx.arc(x, y, radius + 5, 0, 2 * Math.PI);
ctx.strokeStyle = '#d4a017';
ctx.lineWidth = 2;
ctx.stroke();
}
}
// ---------- 绘制整个棋盘和棋子 ----------
function render() {
drawBoard();
for (let r = 0; r < ROWS; r++) {
for (let c = 0; c < COLS; c++) {
const piece = board[r][c];
if (piece) {
const isSel = selected && selected.row === r && selected.col === c;
drawPiece(r, c, piece, isSel);
}
}
}
}
// ---------- 初始化 / 重置游戏 ----------
function resetGame() {
board = cloneBoard(INIT_BOARD);
currentPlayer = RED;
selected = null;
gameOver = false;
waitingForAI = false;
turnText.innerText = '红方走棋';
render();
}
// ---------- 鼠标点击处理 ----------
function handleCanvasClick(e) {
if (gameOver || waitingForAI) return;
const rect = canvas.getBoundingClientRect();
const scaleX = canvas.width / rect.width;
const scaleY = canvas.height / rect.height;
const mouseX = (e.clientX - rect.left) * scaleX;
const mouseY = (e.clientY - rect.top) * scaleY;
// 计算最近的格子
let minDist = Infinity;
let targetRow = -1, targetCol = -1;
for (let r = 0; r < ROWS; r++) {
for (let c = 0; c < COLS; c++) {
const cx = MARGIN_X + c * CELL_SIZE;
const cy = MARGIN_Y + r * CELL_SIZE;
const dist = Math.hypot(mouseX - cx, mouseY - cy);
if (dist < minDist && dist < CELL_SIZE * 0.5) {
minDist = dist;
targetRow = r;
targetCol = c;
}
}
}
if (targetRow === -1) return; // 点击不在有效范围
const clickedPiece = board[targetRow][targetCol];
// 如果已有选中棋子
if (selected) {
// 如果点击的是当前选中的棋子,取消选中
if (selected.row === targetRow && selected.col === targetCol) {
selected = null;
render();
return;
}
// 检查是否移动到目标位置(合法走法)
const legalMoves = generateLegalMoves(board, currentPlayer);
const move = legalMoves.find(m =>
m.from.row === selected.row && m.from.col === selected.col &&
m.to.row === targetRow && m.to.col === targetCol
);
if (move) {
// 执行移动
applyMove(board, selected, { row: targetRow, col: targetCol });
selected = null;
render();
// 检查游戏是否结束
if (checkGameOver()) {
render();
return;
}
// 切换玩家
switchPlayer();
render();
// 如果切换到黑方(AI)并且游戏未结束,触发AI
if (!gameOver && currentPlayer === BLACK) {
waitingForAI = true;
setTimeout(() => {
if (!gameOver && currentPlayer === BLACK) {
makeAIMove();
}
waitingForAI = false;
}, 150);
}
return;
} else {
// 如果点击的是己方棋子,重新选中
const piece = board[targetRow][targetCol];
if (piece && ((currentPlayer && isRed(piece)) || (!currentPlayer && isBlack(piece)))) {
selected = { row: targetRow, col: targetCol };
render();
} else {
// 无效走法,取消选中
selected = null;
render();
}
return;
}
} else {
// 没有选中棋子:尝试选中当前玩家的棋子
if (clickedPiece && ((currentPlayer && isRed(clickedPiece)) || (!currentPlayer && isBlack(clickedPiece)))) {
selected = { row: targetRow, col: targetCol };
render();
}
// 否则忽略
}
}
// ---------- 简单 AI (极小极大 + 简单评估,深度2) ----------
function makeAIMove() {
if (gameOver || currentPlayer !== BLACK) return;
const legalMoves = generateLegalMoves(board, BLACK);
if (legalMoves.length === 0) {
checkGameOver();
render();
return;
}
// 简单评估: 优先吃子,并使用简单子力价值
const pieceValue = {
'k': 10000, 'K': 10000,
'r': 900, 'R': 900,
'c': 450, 'C': 450,
'n': 400, 'N': 400,
'b': 200, 'B': 200,
'a': 200, 'A': 200,
'p': 100, 'P': 100
};
// 使用深度2的极小极大搜索 (黑方最大化,红方最小化)
function evaluateBoard(b) {
let score = 0;
for (let r = 0; r < ROWS; r++) {
for (let c = 0; c < COLS; c++) {
const p = b[r][c];
if (!p) continue;
const val = pieceValue[p] || 0;
if (isBlack(p)) score += val; // 黑方正分
else score -= val; // 红方负分
}
}
return score;
}
// 极小极大 (depth: 剩余深度)
function minimax(b, depth, alpha, beta, maximizingPlayer) {
if (depth === 0) {
return evaluateBoard(b);
}
const color = maximizingPlayer ? BLACK : RED;
const moves = generateLegalMoves(b, color);
if (moves.length === 0) {
// 无棋可走,对当前方不利
return maximizingPlayer ? -Infinity : Infinity;
}
if (maximizingPlayer) {
let maxEval = -Infinity;
for (let move of moves) {
const newBoard = cloneBoard(b);
applyMove(newBoard, move.from, move.to);
const evalScore = minimax(newBoard, depth - 1, alpha, beta, false);
maxEval = Math.max(maxEval, evalScore);
alpha = Math.max(alpha, evalScore);
if (beta <= alpha) break;
}
return maxEval;
} else {
let minEval = Infinity;
for (let move of moves) {
const newBoard = cloneBoard(b);
applyMove(newBoard, move.from, move.to);
const evalScore = minimax(newBoard, depth - 1, alpha, beta, true);
minEval = Math.min(minEval, evalScore);
beta = Math.min(beta, evalScore);
if (beta <= alpha) break;
}
return minEval;
}
}
// 搜索深度2 (黑方走一步,红方回应一步)
let bestMove = legalMoves[0];
let bestScore = -Infinity;
for (let move of legalMoves) {
const newBoard = cloneBoard(board);
applyMove(newBoard, move.from, move.to);
// 检查是否直接吃将
if (newBoard[move.to.row][move.to.col] === 'K') {
bestMove = move;
break;
}
const score = minimax(newBoard, 1, -Infinity, Infinity, false);
if (score > bestScore) {
bestScore = score;
bestMove = move;
}
}
// 执行AI走法
applyMove(board, bestMove.from, bestMove.to);
selected = null;
render();
if (checkGameOver()) {
render();
return;
}
switchPlayer();
render();
}
// ---------- 事件绑定和启动 ----------
canvas.addEventListener('click', handleCanvasClick);
document.getElementById('restartBtn').addEventListener('click', () => {
resetGame();
});
// 初始化
resetGame();
render();
})();
</script>
</body>
</html>
```点击放大试玩
查看完整源码
```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: "Microsoft YaHei", sans-serif;
background: #f0f0f0;
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
color: #333;
}
h1 {
margin-bottom: 15px;
color: #c00;
text-shadow: 1px 1px 2px rgba(0,0,0,0.2);
}
.game-container {
display: flex;
flex-direction: column;
align-items: center;
gap: 15px;
}
.status-bar {
font-size: 18px;
font-weight: bold;
padding: 8px 20px;
background: #fff;
border-radius: 6px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
min-width: 200px;
text-align: center;
}
.red-turn { color: #c00; }
.black-turn { color: #000; }
.board-container {
position: relative;
margin: 0 auto;
}
#chessboard {
background: #f9f2e9;
border: 2px solid #8b4513;
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
}
.controls {
margin-top: 10px;
}
button {
background: #4CAF50;
color: white;
border: none;
padding: 10px 20px;
font-size: 16px;
border-radius: 4px;
cursor: pointer;
margin: 0 5px;
transition: background 0.2s;
}
button:hover {
background: #45a049;
}
button:active {
transform: scale(0.98);
}
.highlight {
position: absolute;
border: 2px solid #ffcc00;
border-radius: 50%;
pointer-events: none;
z-index: 10;
}
.valid-move {
position: absolute;
width: 20px;
height: 20px;
background: rgba(255, 204, 0, 0.7);
border-radius: 50%;
pointer-events: none;
z-index: 5;
}
.captured-area {
display: flex;
gap: 4px;
margin-top: 8px;
flex-wrap: wrap;
max-width: 500px;
justify-content: center;
}
.captured-piece {
width: 30px;
height: 30px;
font-size: 24px;
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
}
.captured-red { color: #c00; }
.captured-black { color: #000; }
.instructions {
margin-top: 15px;
font-size: 14px;
color: #666;
text-align: center;
max-width: 500px;
line-height: 1.5;
}
@media (max-width: 500px) {
#chessboard { width: 90vw; height: auto; }
}
</style>
</head>
<body>
<h1>中国象棋</h1>
<div class="game-container">
<div class="status-bar" id="status">轮到:<span class="red-turn">红方</span></div>
<div class="board-container">
<canvas id="chessboard" width="500" height="550"></canvas>
</div>
<div class="controls">
<button id="restartBtn">重新开始</button>
</div>
<div class="captured-area" id="capturedRed"></div>
<div class="captured-area" id="capturedBlack"></div>
<div class="instructions">
点击棋子选择,再点击目标位置移动。红方先手,AI为黑方(难度中等)。支持马蹩腿、象塞眼、炮翻山、将帅照面等规则。
</div>
</div>
<script>
// 棋盘尺寸与坐标映射
const BOARD_WIDTH = 500;
const BOARD_HEIGHT = 550;
const COL_SPAN = BOARD_WIDTH / 8; // 9列 → 8间隔
const ROW_SPAN = BOARD_HEIGHT / 9; // 10行 → 9间隔
const OFFSET_X = 25;
const OFFSET_Y = 25;
// 坐标转换:棋盘索引 -> 像素
function getPixelX(col) { return OFFSET_X + col * COL_SPAN; }
function getPixelY(row) { return OFFSET_Y + row * ROW_SPAN; }
// 像素 -> 棋盘索引(取整)
function getCol(x) { return Math.round((x - OFFSET_X) / COL_SPAN); }
function getRow(y) { return Math.round((y - OFFSET_Y) / ROW_SPAN); }
// 棋子定义
const PIECES = {
R: { name: '车', color: 'red' },
H: { name: '马', color: 'red' },
E: { name: '相', color: 'red' },
A: { name: '仕', color: 'red' },
G: { name: '帅', color: 'red' },
C: { name: '炮', color: 'red' },
P: { name: '兵', color: 'red' },
r: { name: '车', color: 'black' },
h: { name: '马', color: 'black' },
e: { name: '象', color: 'black' },
a: { name: '士', color: 'black' },
g: { name: '将', color: 'black' },
c: { name: '炮', color: 'black' },
p: { name: '卒', color: 'black' }
};
// 初始化棋盘状态(10行×9列),空位为 null
function initBoard() {
const board = Array(10).fill().map(() => Array(9).fill(null));
// 红方(底部)
board[0] = ['R','H','E','A','G','A','E','H','R'];
board[1] = [null,'C',null,null,null,null,null,'C',null];
board[2] = ['P','P','P','P','P','P','P','P','P'];
// 黑方(顶部)
board[9] = ['r','h','e','a','g','a','e','h','r'];
board[8] = [null,'c',null,null,null,null,null,'c',null];
board[7] = ['p','p','p','p','p','p','p','p','p'];
return board;
}
// 游戏状态
let board = initBoard();
let selected = null; // {row, col}
let validMoves = [];
let currentPlayer = 'red'; // 'red' or 'black'
let capturedRed = [];
let capturedBlack = [];
let gameOver = false;
let aiThinking = false;
// 获取棋子颜色
function getColor(piece) {
if (!piece) return null;
return piece >= 'A' && piece <= 'Z' ? 'red' : 'black';
}
// 判断是否在九宫格内(用于将/帅/士/仕)
function inPalace(row, col, color) {
if (color === 'red') {
return row >= 0 && row <= 2 && col >= 3 && col <= 5;
} else {
return row >= 7 && row <= 9 && col >= 3 && col <= 5;
}
}
// 判断是否在己方半场(用于相/象)
function inOwnSide(row, color) {
return color === 'red' ? row <= 4 : row >= 5;
}
// 判断两点间是否有子(用于车、炮、将帅照面)
function hasPieceBetween(r1, c1, r2, c2) {
const dr = r2 > r1 ? 1 : r2 < r1 ? -1 : 0;
const dc = c2 > c1 ? 1 : c2 < c1 ? -1 : 0;
let r = r1 + dr;
let c = c1 + dc;
while (r !== r2 || c !== c2) {
if (board[r][c] !== null) return true;
r += dr;
c += dc;
}
return false;
}
// 判断是否被将军(检查当前color的将/帅是否被攻击)
function isCheck(color) {
// 找到将/帅位置
let kingPos = null;
for (let r = 0; r < 10; r++) {
for (let c = 0; c < 9; c++) {
const piece = board[r][c];
if (piece && ((color === 'red' && piece === 'G') || (color === 'black' && piece === 'g'))) {
kingPos = { r, c };
break;
}
}
if (kingPos) break;
}
if (!kingPos) return false;
// 检查对方所有棋子能否吃掉将/帅
const enemyColor = color === 'red' ? 'black' : 'red';
for (let r = 0; r < 10; r++) {
for (let c = 0; c < 9; c++) {
const piece = board[r][c];
if (piece && getColor(piece) === enemyColor) {
if (isValidMove(r, c, kingPos.r, kingPos.c, false)) {
return true;
}
}
}
}
return false;
}
// 检查走法是否合法(不考虑将军)
function isValidMove(fromR, fromC, toR, toC, checkCheck = true) {
if (toR < 0 || toR > 9 || toC < 0 || toC > 8) return false;
const piece = board[fromR][fromC];
if (!piece) return false;
const color = getColor(piece);
const target = board[toR][toC];
if (target && getColor(target) === color) return false; // 不能吃己方
// 将/帅规则
if (piece === 'G' || piece === 'g') {
if (!inPalace(toR, toC, color)) return false;
if (Math.abs(fromR - toR) + Math.abs(fromC - toC) !== 1) return false;
// 将帅照面(同列且中间无子)
if (fromC === toC) {
let r1 = color === 'red' ? 0 : 9;
let r2 = color === 'red' ? 9 : 0;
if (fromC === toC) {
const minR = Math.min(fromR, toR);
const maxR = Math.max(fromR, toR);
let hasBetween = false;
for (let r = minR + 1; r < maxR; r++) {
if (board[r][fromC] !== null) {
hasBetween = true;
break;
}
}
if (!hasBetween) {
// 检查对方将/帅是否在同列且无遮挡
let enemyKingR = -1;
for (let r = (color === 'red' ? 0 : 7); r <= (color === 'red' ? 2 : 9); r++) {
if (color === 'red') {
if (board[r][fromC] === 'g') enemyKingR = r;
} else {
if (board[r][fromC] === 'G') enemyKingR = r;
}
}
if (enemyKingR !== -1) {
const minKR = Math.min(enemyKingR, fromR);
const maxKR = Math.max(enemyKingR, fromR);
let enemyHasBetween = false;
for (let r = minKR + 1; r < maxKR; r++) {
if (board[r][fromC] !== null) {
enemyHasBetween = true;
break;
}
}
if (!enemyHasBetween) return false; // 照面禁止
}
}
}
}
return true;
}
// 士/仕
if (piece === 'A' || piece === 'a') {
if (!inPalace(toR, toC, color)) return false;
if (Math.abs(fromR - toR) !== 1 || Math.abs(fromC - toC) !== 1) return false;
return true;
}
// 相/象
if (piece === 'E' || piece === 'e') {
if (!inOwnSide(toR, color)) return false;
const dr = Math.abs(fromR - toR);
const dc = Math.abs(fromC - toC);
if (dr !== 2 || dc !== 2) return false;
// 象眼
const eyeR = (fromR + toR) / 2;
const eyeC = (fromC + toC) / 2;
if (board[eyeR][eyeC] !== null) return false;
return true;
}
// 马
if (piece === 'H' || piece === 'h') {
const dr = Math.abs(fromR - toR);
const dc = Math.abs(fromC - toC);
if (!((dr === 2 && dc === 1) || (dr === 1 && dc === 2))) return false;
// 蹩马腿
if (dr === 2) {
const midR = fromR < toR ? fromR + 1 : fromR - 1;
if (board[midR][fromC] !== null) return false;
} else {
const midC = fromC < toC ? fromC + 1 : fromC - 1;
if (board[fromR][midC] !== null) return false;
}
return true;
}
// 车
if (piece === 'R' || piece === 'r') {
if (fromR !== toR && fromC !== toC) return false;
if (hasPieceBetween(fromR, fromC, toR, toC)) return false;
return true;
}
// 炮
if (piece === 'C' || piece === 'c') {
if (fromR !== toR && fromC !== toC) return false;
const between = hasPieceBetween(fromR, fromC, toR, toC);
if (target === null) {
return !between;
} else {
return between;
}
}
// 兵/卒
if (piece === 'P' || piece === 'p') {
const dr = toR - fromR;
const dc = Math.abs(toC - fromC);
if (dc > 1) return false;
if (color === 'red') {
if (dr !== 1) return false;
if (fromR >= 5 && dr !== 0 && dc !== 1) return false; // 过河后可横
if (fromR < 5 && (dc !== 0 || dr !== 1)) return false;
} else {
if (dr !== -1) return false;
if (fromR <= 4 && dr !== 0 && dc !== 1) return false;
if (fromR > 4 && (dc !== 0 || dr !== -1)) return false;
}
return true;
}
return false;
}
// 获取所有合法移动(用于高亮和AI)
function getValidMoves(row, col) {
const moves = [];
const piece = board[row][col];
if (!piece) return moves;
const color = getColor(piece);
for (let r = 0; r < 10; r++) {
for (let c = 0; c < 9; c++) {
if (isValidMove(row, col, r, c, false)) {
// 模拟走子,检查是否导致己方被将军
const original = board[r][c];
board[r][c] = piece;
board[row][col] = null;
if (!isCheck(color)) {
moves.push({ r, c });
}
// 恢复
board[r][c] = original;
board[row][col] = piece;
}
}
}
return moves;
}
// 执行移动
function makeMove(fromR, fromC, toR, toC) {
const piece = board[fromR][fromC];
const target = board[toR][toC];
if (target) {
if (getColor(target) === 'red') {
capturedRed.push(target);
} else {
capturedBlack.push(target);
}
}
board[toR][toC] = piece;
board[fromR][fromC] = null;
// 检查是否获胜(将死)
const nextPlayer = currentPlayer === 'red' ? 'black' : 'red';
if (isCheck(nextPlayer)) {
// 检查对方是否无合法应将
let canEscape = false;
for (let r = 0; r < 10 && !canEscape; r++) {
for (let c = 0; c < 9 && !canEscape; c++) {
if (board[r][c] && getColor(board[r][c]) === nextPlayer) {
const moves = getValidMoves(r, c);
if (moves.length > 0) canEscape = true;
}
}
}
if (!canEscape) {
gameOver = true;
document.getElementById('status').innerHTML =
`游戏结束!<span class="${currentPlayer === 'red' ? 'red-turn' : 'black-turn'}">${currentPlayer === 'red' ? '红方' : '黑方'}</span>获胜!`;
return;
}
}
}
// 绘制棋盘
function drawBoard() {
const canvas = document.getElementById('chessboard');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, BOARD_WIDTH, BOARD_HEIGHT);
// 绘制背景
ctx.fillStyle = '#f9f2e9';
ctx.fillRect(0, 0, BOARD_WIDTH, BOARD_HEIGHT);
// 绘制线条
ctx.strokeStyle = '#8b4513';
ctx.lineWidth = 1.5;
// 横线(10条)
for (let i = 0; i <= 9; i++) {
const y = OFFSET_Y + i * ROW_SPAN;
ctx.beginPath();
ctx.moveTo(OFFSET_X, y);
ctx.lineTo(OFFSET_X + 8 * COL_SPAN, y);
ctx.stroke();
}
// 纵线(9条)
for (let i = 0; i <= 8; i++) {
const x = OFFSET_X + i * COL_SPAN;
ctx.beginPath();
ctx.moveTo(x, OFFSET_Y);
ctx.lineTo(x, OFFSET_Y + 9 * ROW_SPAN);
ctx.stroke();
}
// 河界(第5-6行之间)
ctx.fillStyle = '#add8e6';
ctx.fillRect(OFFSET_X, OFFSET_Y + 4.5 * ROW_SPAN, 8 * COL_SPAN, ROW_SPAN);
ctx.font = 'bold 16px Arial';
ctx.fillStyle = '#000';
ctx.textAlign = 'center';
ctx.fillText('楚 河', OFFSET_X + 4 * COL_SPAN, OFFSET_Y + 4.8 * ROW_SPAN);
ctx.fillText('汉 界', OFFSET_X + 4 * COL_SPAN, OFFSET_Y + 5.3 * ROW_SPAN);
// 九宫格(红方)
ctx.beginPath();
ctx.moveTo(OFFSET_X + 3 * COL_SPAN, OFFSET_Y);
ctx.lineTo(OFFSET_X + 5 * COL_SPAN, OFFSET_Y);
ctx.moveTo(OFFSET_X + 3 * COL_SPAN, OFFSET_Y + 2 * ROW_SPAN);
ctx.lineTo(OFFSET_X + 5 * COL_SPAN, OFFSET_Y + 2 * ROW_SPAN);
ctx.moveTo(OFFSET_X + 3 * COL_SPAN, OFFSET_Y);
ctx.lineTo(OFFSET_X + 3 * COL_SPAN, OFFSET_Y + 2 * ROW_SPAN);
ctx.moveTo(OFFSET_X + 5 * COL_SPAN, OFFSET_Y);
ctx.lineTo(OFFSET_X + 5 * COL_SPAN, OFFSET_Y + 2 * ROW_SPAN);
ctx.moveTo(OFFSET_X + 4 * COL_SPAN, OFFSET_Y);
ctx.lineTo(OFFSET_X + 4 * COL_SPAN, OFFSET_Y + 2 * ROW_SPAN);
ctx.stroke();
// 九宫格(黑方)
ctx.beginPath();
ctx.moveTo(OFFSET_X + 3 * COL_SPAN, OFFSET_Y + 7 * ROW_SPAN);
ctx.lineTo(OFFSET_X + 5 * COL_SPAN, OFFSET_Y + 7 * ROW_SPAN);
ctx.moveTo(OFFSET_X + 3 * COL_SPAN, OFFSET_Y + 9 * ROW_SPAN);
ctx.lineTo(OFFSET_X + 5 * COL_SPAN, OFFSET_Y + 9 * ROW_SPAN);
ctx.moveTo(OFFSET_X + 3 * COL_SPAN, OFFSET_Y + 7 * ROW_SPAN);
ctx.lineTo(OFFSET_X + 3 * COL_SPAN, OFFSET_Y + 9 * ROW_SPAN);
ctx.moveTo(OFFSET_X + 5 * COL_SPAN, OFFSET_Y + 7 * ROW_SPAN);
ctx.lineTo(OFFSET_X + 5 * COL_SPAN, OFFSET_Y + 9 * ROW_SPAN);
ctx.moveTo(OFFSET_X + 4 * COL_SPAN, OFFSET_Y + 7 * ROW_SPAN);
ctx.lineTo(OFFSET_X + 4 * COL_SPAN, OFFSET_Y + 9 * ROW_SPAN);
ctx.stroke();
// 绘制斜线(九宫内)
ctx.beginPath();
ctx.moveTo(OFFSET_X + 3 * COL_SPAN, OFFSET_Y);
ctx.lineTo(OFFSET_X + 5 * COL_SPAN, OFFSET_Y + 2 * ROW_SPAN);
ctx.moveTo(OFFSET_X + 5 * COL_SPAN, OFFSET_Y);
ctx.lineTo(OFFSET_X + 3 * COL_SPAN, OFFSET_Y + 2 * ROW_SPAN);
ctx.moveTo(OFFSET_X + 3 * COL_SPAN, OFFSET_Y + 7 * ROW_SPAN);
ctx.lineTo(OFFSET_X + 5 * COL_SPAN, OFFSET_Y + 9 * ROW_SPAN);
ctx.moveTo(OFFSET_X + 5 * COL_SPAN, OFFSET_Y + 7 * ROW_SPAN);
ctx.lineTo(OFFSET_X + 3 * COL_SPAN, OFFSET_Y + 9 * ROW_SPAN);
ctx.stroke();
// 绘制棋子
ctx.font = 'bold 24px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
for (let r = 0; r < 10; r++) {
for (let c = 0; c < 9; c++) {
const piece = board[r][c];
if (piece) {
const x = getPixelX(c);
const y = getPixelY(r);
const info = PIECES[piece];
ctx.fillStyle = info.color === 'red' ? '#c00' : '#000';
ctx.beginPath();
ctx.arc(x, y, 16, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = '#fff';
ctx.lineWidth = 2;
ctx.stroke();
ctx.fillStyle = '#fff';
ctx.fillText(info.name, x, y);
}
}
}
// 绘制选中高亮
if (selected) {
const { r, c } = selected;
const x = getPixelX(c);
const y = getPixelY(r);
const highlight = document.createElement('div');
highlight.className = 'highlight';
highlight.style.left = (x - 18) + 'px';
highlight.style.top = (y - 18) + 'px';
highlight.style.width = '36px';
highlight.style.height = '36px';
document.querySelector('.board-container').appendChild(highlight);
}
// 绘制合法移动点
validMoves.forEach(move => {
const x = getPixelX(move.c);
const y = getPixelY(move.r);
const dot = document.createElement('div');
dot.className = 'valid-move';
dot.style.left = (x - 10) + 'px';
dot.style.top = (y - 10) + 'px';
document.querySelector('.board-container').appendChild(dot);
});
}
// 清除高亮
function clearHighlights() {
document.querySelectorAll('.highlight, .valid-move').forEach(el => el.remove());
}
// AI 简单逻辑(随机合法走法,优先吃子、将军)
function aiMove() {
if (gameOver || aiThinking) return;
aiThinking = true;
// 收集所有黑方棋子的合法移动
const moves = [];
for (let r = 0; r < 10; r++) {
for (let c = 0; c < 9; c++) {
const piece = board[r][c];
if (piece && getColor(piece) === 'black') {
const valid = getValidMoves(r, c);
for (const move of valid) {
moves.push({ fromR: r, fromC: c, toR: move.r, toC: move.c });
}
}
}
}
if (moves.length === 0) {
aiThinking = false;
return;
}
// 评分:吃子 > 将军 > 随机
let bestMoves = [];
let maxScore = -1;
for (const move of moves) {
const target = board[move.toR][move.toC];
let score = 0;
if (target) score += 100; // 吃子
// 检查是否将军
const original = board[move.toR][move.toC];
board[move.toR][move.toC] = board[move.fromR][move.fromC];
board[move.fromR][move.fromC] = null;
if (isCheck('red')) score += 50;
// 恢复
board[move.toR][move.toC] = original;
board[move.fromR][move.fromC] = board[move.toR][move.toC];
if (score > maxScore) {
maxScore = score;
bestMoves = [move];
} else if (score === maxScore) {
bestMoves.push(move);
}
}
// 随机选一个
const chosen = bestMoves[Math.floor(Math.random() * bestMoves.length)];
setTimeout(() => {
makeMove(chosen.fromR, chosen.fromC, chosen.toR, chosen.toC);
currentPlayer = 'red';
updateStatus();
aiThinking = false;
}, 600);
}
// 更新状态栏
function updateStatus() {
const statusEl = document.getElementById('status');
if (gameOver) return;
if (currentPlayer === 'red') {
statusEl.innerHTML = '轮到:<span class="red-turn">红方</span>';
} else {
statusEl.innerHTML = '轮到:<span class="black-turn">黑方</span>';
}
}
// 更新俘获区
function updateCaptured() {
const redEl = document.getElementById('capturedRed');
const blackEl = document.getElementById('capturedBlack');
redEl.innerHTML = '';
blackEl.innerHTML = '';
capturedRed.forEach(p => {
const span = document.createElement('span');
span.className = 'captured-piece captured-red';
span.textContent = PIECES[p].name;
redEl.appendChild(span);
});
capturedBlack.forEach(p => {
const span = document.createElement('span');
span.className = 'captured-piece captured-black';
span.textContent = PIECES[p].name;
blackEl.appendChild(span);
});
}
// 事件处理
document.getElementById('chessboard').addEventListener('click', (e) => {
if (gameOver || currentPlayer !== 'red' || aiThinking) return;
const rect = document.getElementById('chessboard').getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const col = getCol(x);
const row = getRow(y);
if (row < 0 || row > 9 || col < 0 || col > 8) return;
// 点击已选中的棋子 -> 取消选择
if (selected && selected.r === row && selected.c === col) {
clearHighlights();
selected = null;
validMoves = [];
return;
}
const piece = board[row][col];
// 选择己方棋子
if (piece && getColor(piece) === 'red') {
clearHighlights();
selected = { r: row, c: col };
validMoves = getValidMoves(row, col);
return;
}
// 尝试移动
if (selected) {
const valid = validMoves.some(m => m.r === row && m.c === col);
if (valid) {
makeMove(selected.r, selected.c, row, col);
currentPlayer = 'black';
updateStatus();
clearHighlights();
selected = null;
validMoves = [];
// 延迟AI走子(避免卡顿)
setTimeout(aiMove, 300);
}
}
});
document.getElementById('restartBtn').addEventListener('click', () => {
board = initBoard();
selected = null;
validMoves = [];
currentPlayer = 'red';
capturedRed = [];
capturedBlack = [];
gameOver = false;
aiThinking = false;
clearHighlights();
updateStatus();
updateCaptured();
});
// 初始化
function init() {
updateStatus();
updateCaptured();
}
// 游戏循环
function gameLoop() {
clearHighlights();
drawBoard();
requestAnimationFrame(gameLoop);
}
// 启动
init();
gameLoop();
</script>
</body>
</html>
```点击放大试玩
查看完整源码
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>中国象棋</title>
<style>
body { font-family: Arial, sans-serif; }
#chessboard { display: grid; grid-template-columns: repeat(10, 50px); grid-template-rows: repeat(9, 50px); }
.square { width: 50px; height: 50px; position: relative; }
.piece { position: absolute; width: 40px; height: 40px; }
.red { color: red; }
.black { color: black; }
.rook { background: url('rook.png') no-repeat center center; }
.horse { background: url('horse.png') no-repeat center center; }
.cannon { background: url('cannon.png') no-repeat center center; }
.elephant { background: url('elephant.png') no-repeat center center; }
.soldier { background: url('soldier.png') no-repeat center center; }
.chariot { background: url('chariot.png') no-repeat center center; }
.advisor { background: url('advisor.png') no-repeat center center; }
.general { background: url('general.png') no-repeat center center; }
.knight { background: url('knight.png') no-repeat center center; }
.button { margin-top: 10px; }
</style>
</head>
<body>
<div id="chessboard"></div>
<button id="restart">重新开始</button>
<div id="turn">红方回合</div>
<script>
const board = [
['r', 'n', 'b', 'c', 'p', 'c', 'b', 'n', 'r'],
['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
['', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', ''],
['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'],
['R', 'N', 'B', 'C', 'P', 'C', 'B', 'N', 'R'],
];
const pieceImages = {
r: 'rook.png',
n: 'horse.png',
b: 'elephant.png',
c: 'cannon.png',
p: 'soldier.png',
R: 'rook.png',
N: 'horse.png',
B: 'elephant.png',
C: 'cannon.png',
P: 'soldier.png',
c: 'chariot.png',
a: 'advisor.png',
g: 'general.png',
k: 'knight.png',
};
const directions = {
r: [0, 1], n: [-1, 2, -2, 1], b: [-1, -2, 1, 2], c: [1, 1], p: [1], C: [1, -1], R: [0, 1], N: [-1, 2, -2, 1], B: [-1, -2, 1, 2], C: [1, 1], P: [1], r: [0, 1], n: [-1, 2, -2, 1], b: [-1, -2, 1, 2], c: [1, 1], p: [1],
};
const validMoves = {
r: (x, y) => [0, 1].every(d => board[y][x + d] === ''), n: (x, y) => directions.n.some(([dx, dy]) => board[y + dy][x + dx] === ''), b: (x, y) => directions.b.some(([dx, dy]) => board[y + dy][x + dx] === ''), c: (x, y) => directions.c.some(([dx, dy]) => board[y + dy][x + dx] === ''), p: (x, y) => directions.p.some(([dy]) => board[y + dy][x] === ''), C: (x, y) => directions.C.some(([dx, dy]) => board[y + dy][x + dx] === ''), R: (x, y) => [0, 1].every(d => board[y][x + d] === ''), N: (x, y) => directions.N.some(([dx, dy]) => board[y + dy][x + dx] === ''), B: (x, y) => directions.B.some(([dx, dy]) => board[y + dy][x + dx] === ''), C: (x, y) => directions.C.some(([dx, dy]) => board[y + dy][x + dx] === ''), P: (x, y) => directions.P.some(([dy]) => board[y + dy][x] === ''), r: (x, y) => [0, 1].every(d => board[y][x + d] === ''), n: (x, y) => directions.n.some(([dx, dy]) => board[y + dy][x + dx] === ''), b: (x, y) => directions.b.some(([dx, dy]) => board[y + dy][x + dx] === ''), c: (x, y) => directions.c.some(([dx, dy]) => board[y + dy][x + dx] === ''), p: (x, y) => directions.p.some(([dy]) => board[y + dy][x] === ''),
};
const isEnemy = (x, y, color) => board[y][x] !== '' && board[y][x].toUpperCase() !== color;
const isSameColor = (x, y, color) => board[y][x] !== '' && board[y][x].toUpperCase() === color;
const isCheck = (color) => {
const kingPos = color === 'red' ? board[0].indexOf('g') : board[8].indexOf('G');
const enemyMoves = board.flat().reduce((acc, piece, index) => {
const [x, y] = [index % 9, Math.floor(index / 9)];
if (piece === '') return acc;
const moves = validMoves[board[y][x]];
if (moves) {
const validMoves = moves(x, y).filter(([mx, my]) => mx >= 0 && mx < 9 && my >= 0 && my < 9);
validMoves.forEach(([mx, my]) => {
const newBoard = [...board];
newBoard[my][mx] = piece;
newBoard[y][x] = '';
if (newBoard[my][mx].toUpperCase() === 'G' || newBoard[my][mx].toUpperCase() === 'G') {
acc.push([mx, my]);
}
});
}
return acc;
}, []);
return enemyMoves.some(([mx, my]) => mx === kingPos % 9 && my === kingPos / 9);
};
const isCheckmate = (color) => {
const kingPos = color === 'red' ? board[0].indexOf('g') : board[8].indexOf('G');
const enemyMoves = board.flat().reduce((acc, piece, index) => {
const [x, y] = [index % 9, Math.floor(index / 9)];
if (piece === '') return acc;
const moves = validMoves[board[y][x]];
if (moves) {
const validMoves = moves(x, y).filter(([mx, my]) => mx >= 0 && mx < 9 && my >= 0 && my < 9);
validMoves.forEach(([mx, my]) => {
const newBoard = [...board];
newBoard[my][mx] = piece;
newBoard[y][x] = '';
if (newBoard[my][mx].toUpperCase() === 'G' || newBoard[my][mx].toUpperCase() === 'G') {
acc.push([mx, my]);
}
});
}
return acc;
}, []);
return enemyMoves.length === 0 && isCheck(color);
};
const aiMove = (color) => {
const kingPos = color === 'red' ? board[0].indexOf('g') : board[8].indexOf('G');
const enemyMoves = board.flat().reduce((acc, piece, index) => {
const [x, y] = [index % 9, Math.floor(index / 9)];
if (piece === '') return acc;
const moves = validMoves[board[y][x]];
if (moves) {
const validMoves = moves(x, y).filter(([mx, my]) => mx >= 0 && mx < 9 && my >= 0 && my < 9);
validMoves.forEach(([mx, my]) => {
const newBoard = [...board];
newBoard[my][mx] = piece;
newBoard[y][x] = '';
if (newBoard[my][mx].toUpperCase() === 'G' || newBoard[my][mx].toUpperCase() === 'G') {
acc.push([mx, my]);
}
});
}
return acc;
}, []);
if (enemyMoves.length === 0) return;
const bestMove = enemyMoves.reduce((best, move) => {
const newBoard = [...board];
newBoard[move[1]][move[0]] = board[board[8].indexOf('G') % 9][board[8].indexOf('G') / 9];
newBoard[board[8].indexOf('G') % 9][board[8].indexOf('G') / 9] = '';
if (isCheckmate('red')) {
return move;
}
return best;
}, enemyMoves[0]);
board[bestMove[1]][bestMove[0]] = board[board[8].indexOf('G') % 9][board[8].indexOf('G') / 9];
board[board[8].indexOf('G') % 9][board[8].indexOf('G') / 9] = '';
};
const renderBoard = () => {
const chessboard = document.getElementById('chessboard');
chessboard.innerHTML = '';
board.forEach((row, y) => {
row.forEach((piece, x) => {
const square = document.createElement('div');
square.className = 'square';
square.style.gridRowStart = y + 1;
square.style.gridColumnStart = x + 1;
if (piece !== '') {
const img = document.createElement('img');
img.className = `piece ${piece.toLowerCase()}`;
img.src = pieceImages[piece];
square.appendChild(img);
}
chessboard.appendChild(square);
});
});
};
const restartGame = () => {
board.fill(['r', 'n', 'b', 'c', 'p', 'c', 'b', 'n', 'r'], 0, 9);
board.fill(['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'], 9, 18);
board.fill('', 18, 27);
board.fill('', 27, 36);
board.fill('', 36, 45);
board.fill(['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'], 45, 54);
board.fill(['R', 'N', 'B', 'C', 'P', 'C', 'B', 'N', 'R'], 54, 63);
renderBoard();
document.getElementById('turn').textContent = '红方回合';
};
const handleClick = (x, y) => {
if (board[y][x] === '') return;
const color = board[y][x].toUpperCase();
const moves = validMoves[board[y][x]][x][y];
const validMoves = moves.filter(([mx, my]) => mx >= 0 && mx < 9 && my >= 0 && my < 9);
const enemyMoves = board.flat().reduce((acc, piece, index) => {
const [ex, ey] = [index % 9, Math.floor(index / 9)];
if (piece === '') return acc;
const moves = validMoves[board[ey][ex]];
if (moves) {
const validMoves = moves(ex, ey).filter(([mx, my]) => mx >= 0 && mx < 9 && my >= 0 && my < 9);
validMoves.forEach(([mx, my]) => {
const newBoard = [...board];
newBoard[my][mx] = piece;
newBoard[ey][ex] = '';
if (newBoard[my][mx].toUpperCase() === 'G' || newBoard[my][mx].toUpperCase() === 'G') {
acc.push([mx, my]);
}
});
}
return acc;
}, []);
validMoves.forEach(([mx, my]) => {
const newBoard = [...board];
newBoard[my][mx] = board[y][x];
newBoard[y][x] = '';
if (isCheck(color)) {
newBoard[my][mx] = '';
newBoard[y][x] = board[y][x];
return;
}
newBoard[my][mx] = board[y][x];
newBoard[y][x] = '';
if (isCheck(color)) {
newBoard[my][mx] = '';
newBoard[y][x] = board[y][x];
return;
}
board = newBoard;
renderBoard();
document.getElementById('turn').textContent = color === 'red' ? '黑方回合' : '红方回合';
if (isCheckmate(color)) {
document.getElementById('turn').textContent = `${color} 胜!`;
}
if (color === 'red') {
setTimeout(() => aiMove('black'), 1000);
}
});
};
const init = () => {
renderBoard();
document.getElementById('restart').addEventListener('click', restartGame);
document.getElementById('chessboard').addEventListener('click', (e) => {
const rect = e.target.getBoundingClientRect();
const x = Math.floor((e.clientX - rect.left) / 50);
const y = Math.floor((e.clientY - rect.top) / 50);
handleClick(x, y);
});
restartGame();
};
init();
</script>
</body>
</html>
```未产出可运行的网页产物
查看完整源码
```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>中国象棋 (Chinese Chess)</title>
<style>
:root {
--board-color: #f0d9b5;
--line-color: #000;
--bg-color: #1a1a1a;
--panel-bg: #2d2d2d;
--text-color: #e0e0e0;
--red-piece: #cc0000;
--black-piece: #1a1a1a;
--highlight: rgba(255, 255, 0, 0.5);
--selected: rgba(0, 255, 0, 0.5);
--move-dot: rgba(0, 0, 0, 0.3);
--accent: #4CAF50;
}
body {
margin: 0;
padding: 0;
background-color: var(--bg-color);
color: var(--text-color);
font-family: 'Microsoft YaHei', 'SimHei', sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
overflow: hidden;
}
h1 {
margin: 10px 0;
font-size: 28px;
letter-spacing: 2px;
text-shadow: 0 2px 4px rgba(0,0,0,0.5);
}
#game-container {
position: relative;
display: flex;
flex-direction: column;
align-items: center;
gap: 15px;
}
#board-wrapper {
position: relative;
box-shadow: 0 10px 30px rgba(0,0,0,0.5);
border-radius: 8px;
overflow: hidden;
background-color: var(--board-color);
}
canvas {
display: block;
cursor: pointer;
}
#status-bar {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
background: var(--panel-bg);
padding: 10px 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0,0,0,0.3);
box-sizing: border-box;
}
.turn-indicator {
display: flex;
align-items: center;
gap: 10px;
font-size: 18px;
font-weight: bold;
}
.turn-piece {
width: 24px;
height: 24px;
border-radius: 50%;
display: inline-block;
border: 2px solid #fff;
box-shadow: 0 0 5px rgba(0,0,0,0.5);
}
.turn-piece.red { background-color: var(--red-piece); }
.turn-piece.black { background-color: var(--black-piece); }
button {
background: var(--accent);
color: white;
border: none;
padding: 8px 20px;
font-size: 16px;
border-radius: 5px;
cursor: pointer;
transition: all 0.2s;
font-family: inherit;
}
button:hover {
background: #45a049;
transform: translateY(-1px);
box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}
button:active {
transform: translateY(0);
}
#message-overlay {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0, 0, 0, 0.85);
padding: 20px 40px;
border-radius: 10px;
font-size: 24px;
font-weight: bold;
display: none;
z-index: 10;
pointer-events: none;
text-align: center;
border: 2px solid var(--accent);
}
.controls {
display: flex;
gap: 10px;
}
</style>
</head>
<body>
<h1>中国象棋</h1>
<div id="game-container">
<div id="board-wrapper">
<canvas id="board"></canvas>
<div id="message-overlay"></div>
</div>
<div id="status-bar">
<div class="turn-indicator">
<span>轮到:</span>
<div class="turn-piece red" id="turn-piece"></div>
<span id="turn-text">红方</span>
</div>
<div class="controls">
<button id="restart-btn">重新开始</button>
</div>
</div>
</div>
<script>
(function() {
// ==================== CONSTANTS & CONFIG ====================
const BOARD_COLS = 9;
const BOARD_ROWS = 10;
const PIECE_RADIUS = 22;
const CELL_SIZE = 52;
const BOARD_PADDING = 35;
const PIECE_TYPES = {
GENERAL: '帅', ADVISOR: '仕', ELEPHANT: '相',
HORSE: '马', CHARIOT: '车', CANNON: '炮', SOLDIER: '兵'
};
const PIECE_NAMES = {
'帅': '将', '仕': '士', '相': '象',
'马': '马', '车': '车', '炮': '炮', '兵': '卒'
};
const RED = 'red';
const BLACK = 'black';
// ==================== INITIAL BOARD SETUP ====================
function createInitialBoard() {
const b = Array(BOARD_ROWS).fill(null).map(() => Array(BOARD_COLS).fill(null));
const backRow = ['车', '马', '相', '仕', '帅', '仕', '相', '马', '车'];
const frontRow = [null, '炮', null, null, null, null, null, '炮', null];
const soldierRow = ['兵', null, '兵', null, '兵', null, '兵', null, '兵'];
// Red side (bottom)
for (let c = 0; c < BOARD_COLS; c++) b[9][c] = { type: backRow[c], color: RED, x: c, y: 9 };
for (let c = 0; c < BOARD_COLS; c++) if (frontRow[c]) b[7][c] = { type: frontRow[c], color: RED, x: c, y: 7 };
for (let c = 0; c < BOARD_COLS; c++) if (soldierRow[c]) b[6][c] = { type: soldierRow[c], color: RED, x: c, y: 6 };
// Black side (top)
for (let c = 0; c < BOARD_COLS; c++) b[0][c] = { type: backRow[c], color: BLACK, x: c, y: 0 };
for (let c = 0; c < BOARD_COLS; c++) if (frontRow[c]) b[2][c] = { type: frontRow[c], color: BLACK, x: c, y: 2 };
for (let c = 0; c < BOARD_COLS; c++) if (soldierRow[c]) b[3][c] = { type: soldierRow[c], color: BLACK, x: c, y: 3 };
return b;
}
// ==================== GAME STATE ====================
let board = createInitialBoard();
let currentPlayer = RED;
let selectedPiece = null;
let gameOver = false;
let isAITurn = false;
let animating = false;
let lastMove = null;
// ==================== CANVAS SETUP ====================
const canvas = document.getElementById('board');
const ctx = canvas.getContext('2d');
const messageOverlay = document.getElementById('message-overlay');
const turnPiece = document.getElementById('turn-piece');
const turnText = document.getElementById('turn-text');
const BOARD_WIDTH = BOARD_PADDING * 2 + CELL_SIZE * (BOARD_COLS - 1);
const BOARD_HEIGHT = BOARD_PADDING * 2 + CELL_SIZE * (BOARD_ROWS - 1);
canvas.width = BOARD_WIDTH;
canvas.height = BOARD_HEIGHT;
// ==================== COORDINATE HELPERS ====================
function toCanvas(x, y) {
return { x: BOARD_PADDING + x * CELL_SIZE, y: BOARD_PADDING + y * CELL_SIZE };
}
function fromCanvas(cx, cy) {
const x = Math.round((cx - BOARD_PADDING) / CELL_SIZE);
const y = Math.round((cy - BOARD_PADDING) / CELL_SIZE);
if (x >= 0 && x < BOARD_COLS && y >= 0 && y < BOARD_ROWS) return { x, y };
return null;
}
// ==================== DRAWING ====================
function drawBoard() {
ctx.fillStyle = '#f0d9b5';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = '#333';
ctx.lineWidth = 1.5;
// Horizontal lines
for (let r = 0; r < BOARD_ROWS; r++) {
const p1 = toCanvas(0, r);
const p2 = toCanvas(BOARD_COLS - 1, r);
ctx.beginPath();
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.y);
ctx.stroke();
}
// Vertical lines (split by river)
for (let c = 0; c < BOARD_COLS; c++) {
const p1 = toCanvas(c, 0);
const p2 = toCanvas(c, 4);
ctx.beginPath();
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.y);
ctx.stroke();
const p3 = toCanvas(c, 5);
const p4 = toCanvas(c, 9);
ctx.beginPath();
ctx.moveTo(p3.x, p3.y);
ctx.lineTo(p4.x, p4.y);
ctx.stroke();
}
// Palace diagonals
ctx.beginPath();
let p = toCanvas(3, 0); ctx.moveTo(p.x, p.y); p = toCanvas(5, 2); ctx.lineTo(p.x, p.y);
p = toCanvas(5, 0); ctx.moveTo(p.x, p.y); p = toCanvas(3, 2); ctx.lineTo(p.x, p.y);
p = toCanvas(3, 7); ctx.moveTo(p.x, p.y); p = toCanvas(5, 9); ctx.lineTo(p.x, p.y);
p = toCanvas(5, 7); ctx.moveTo(p.x, p.y); p = toCanvas(3, 9); ctx.lineTo(p.x, p.y);
ctx.stroke();
// Border
ctx.strokeStyle = '#222';
ctx.lineWidth = 3;
ctx.strokeRect(BOARD_PADDING - 5, BOARD_PADDING - 5,
(BOARD_COLS - 1) * CELL_SIZE + 10,
(BOARD_ROWS - 1) * CELL_SIZE + 10);
// River text
ctx.fillStyle = '#333';
ctx.font = 'bold 28px "Microsoft YaHei", "SimHei", sans-serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
const riverY = (toCanvas(0, 4).y + toCanvas(0, 5).y) / 2;
ctx.fillText('楚 河', BOARD_WIDTH / 2 - 70, riverY);
ctx.fillText('汉 界', BOARD_WIDTH / 2 + 70, riverY);
// Position markers
drawPositionMarkers();
}
function drawPositionMarkers() {
ctx.fillStyle = '#333';
const size = 4;
const offset = CELL_SIZE / 2 - 2;
const positions = [
[1,2],[1,3],[1,6],[1,7],[7,2],[7,3],[7,6],[7,7],
[2,2],[2,7],[4,2],[4,7],[6,2],[6,7]
];
positions.forEach(([x, y]) => {
const p = toCanvas(x, y);
// Left
if (x > 0) {
ctx.beginPath();
ctx.moveTo(p.x - offset, p.y - size); ctx.lineTo(p.x - size, p.y - size);
ctx.lineTo(p.x - size, p.y - offset); ctx.stroke();
ctx.beginPath();
ctx.moveTo(p.x - offset, p.y + size); ctx.lineTo(p.x - size, p.y + size);
ctx.lineTo(p.x - size, p.y + offset); ctx.stroke();
}
// Right
if (x < BOARD_COLS - 1) {
ctx.beginPath();
ctx.moveTo(p.x + offset, p.y - size); ctx.lineTo(p.x + size, p.y - size);
ctx.lineTo(p.x + size, p.y - offset); ctx.stroke();
ctx.beginPath();
ctx.moveTo(p.x + offset, p.y + size); ctx.lineTo(p.x + size, p.y + size);
ctx.lineTo(p.x + size, p.y + offset); ctx.stroke();
}
});
}
function drawPiece(piece, cx, cy, scale = 1) {
const radius = PIECE_RADIUS * scale;
const isRed = piece.color === RED;
// Shadow
ctx.beginPath();
ctx.arc(cx + 2, cy + 2, radius, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(0,0,0,0.3)';
ctx.fill();
// Outer circle
ctx.beginPath();
ctx.arc(cx, cy, radius, 0, Math.PI * 2);
ctx.fillStyle = '#f5f0e1';
ctx.fill();
ctx.strokeStyle = isRed ? '#cc0000' : '#1a1a1a';
ctx.lineWidth = 2;
ctx.stroke();
// Inner circle
ctx.beginPath();
ctx.arc(cx, cy, radius - 4, 0, Math.PI * 2);
ctx.strokeStyle = isRed ? '#cc0000' : '#1a1a1a';
ctx.lineWidth = 1;
ctx.stroke();
// Text
ctx.fillStyle = isRed ? '#cc0000' : '#1a1a1a';
ctx.font = `bold ${Math.floor(22 * scale)}px "Microsoft YaHei", "SimHei", sans-serif`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
const displayText = isRed ? piece.type : (PIECE_NAMES[piece.type] || piece.type);
ctx.fillText(displayText, cx, cy + 1);
}
function drawGame() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBoard();
// Draw last move highlight
if (lastMove) {
const from = toCanvas(lastMove.from.x, lastMove.from.y);
const to = toCanvas(lastMove.to.x, lastMove.to.y);
ctx.fillStyle = 'rgba(255, 165, 0, 0.3)';
ctx.beginPath(); ctx.arc(from.x, from.y, PIECE_RADIUS + 3, 0, Math.PI * 2); ctx.fill();
ctx.beginPath(); ctx.arc(to.x, to.y, PIECE_RADIUS + 3, 0, Math.PI * 2); ctx.fill();
}
// Draw selection highlight
if (selectedPiece) {
const p = toCanvas(selectedPiece.x, selectedPiece.y);
ctx.strokeStyle = '#00ff00';
ctx.lineWidth = 3;
ctx.beginPath();
ctx.arc(p.x, p.y, PIECE_RADIUS + 4, 0, Math.PI * 2);
ctx.stroke();
}
// Draw pieces
for (let y = 0; y < BOARD_ROWS; y++) {
for (let x = 0; x < BOARD_COLS; x++) {
const piece = board[y][x];
if (piece) {
const p = toCanvas(x, y);
drawPiece(piece, p.x, p.y);
}
}
}
}
// ==================== MOVE VALIDATION ====================
function getPieceAt(x, y) {
if (x < 0 || x >= BOARD_COLS || y < 0 || y >= BOARD_ROWS) return null;
return board[y][x];
}
function isLegalMove(fromX, fromY, toX, toY) {
const piece = board[fromY][fromX];
if (!piece) return false;
const target = board[toY][toX];
if (target && target.color === piece.color) return false;
const dx = toX - fromX;
const dy = toY - fromY;
const adx = Math.abs(dx);
const ady = Math.abs(dy);
switch (piece.type) {
case '帅':
case '将':
if (adx > 1 || ady > 1 || adx + ady !== 1) return false;
if (toX < 3 || toX > 5) return false;
if (piece.color === RED && toY < 7) return false;
if (piece.color === BLACK && toY > 2) return false;
// Face to face check handled separately
break;
case '仕':
case '士':
if (adx !== 1 || ady !== 1) return false;
if (toX < 3 || toX > 5) return false;
if (piece.color === RED && toY < 7) return false;
if (piece.color === BLACK && toY > 2) return false;
break;
case '相':
case '象':
if (adx !== 2 || ady !== 2) return false;
// Blocked eye
if (board[fromY + dy/2][fromX + dx/2]) return false;
// Cannot cross river
if (piece.color === RED && toY < 5) return false;
if (piece.color === BLACK && toY > 4) return false;
break;
case '马':
if (!((adx === 1 && ady === 2) || (adx === 2 && ady === 1))) return false;
// Leg blocking
if (adx === 2) { // horizontal move
if (board[fromY][fromX + dx/2]) return false;
} else { // vertical move
if (board[fromY + dy/2][fromX]) return false;
}
break;
case '车':
if (dx !== 0 && dy !== 0) return false;
let count = 0;
if (dx === 0) {
const step = dy > 0 ? 1 : -1;
for (let y = fromY + step; y !== toY; y += step) {
if (board[y][fromX]) count++;
}
} else {
const step = dx > 0 ? 1 : -1;
for (let x = fromX + step; x !== toX; x += step) {
if (board[fromY][x]) count++;
}
}
if (count > 0) return false;
break;
case '炮':
if (dx !== 0 && dy !== 0) return false;
let obstacles = 0;
if (dx === 0) {
const step = dy > 0 ? 1 : -1;
for (let y = fromY + step; y !== toY; y += step) {
if (board[y][fromX]) obstacles++;
}
} else {
const step = dx > 0 ? 1 : -1;
for (let x = fromX + step; x !== toX; x += step) {
if (board[fromY][x]) obstacles++;
}
}
if (target) {
if (obstacles !== 1) return false;
} else {
if (obstacles !== 0) return false;
}
break;
case '兵':
case '卒':
if (adx + ady !== 1) return false;
const crossed = (piece.color === RED && fromY <= 4) || (piece.color === BLACK && fromY >= 5);
if (!crossed) {
// Can only move forward
if (piece.color === RED && dy !== -1) return false;
if (piece.color === BLACK && dy !== 1) return false;
if (dx !== 0) return false;
} else {
// Cannot move backward
if (piece.color === RED && dy === 1) return false;
if (piece.color === BLACK && dy === -1) return false;
}
break;
}
// Check face to face after move
const tempBoard = board.map(row => [...row]);
tempBoard[toY][toX] = { ...piece, x: toX, y: toY };
tempBoard[fromY][fromX] = null;
// Find generals
let redGen = null, blackGen = null;
for (let y = 0; y < BOARD_ROWS; y++) {
for (let x = 0; x < BOARD_COLS; x++) {
const p = tempBoard[y][x];
if (p && (p.type === '帅' || p.type === '将')) {
if (p.color === RED) redGen = { x, y };
else blackGen = { x, y };
}
}
}
if (redGen && blackGen && redGen.x === blackGen.x) {
let blocked = false;
const minY = Math.min(redGen.y, blackGen.y);
const maxY = Math.max(redGen.y, blackGen.y);
for (let y = minY + 1; y < maxY; y++) {
if (tempBoard[y][redGen.x]) { blocked = true; break; }
}
if (!blocked) return false;
}
return true;
}
function isInCheck(color, testBoard = board) {
// Find general
let genPos = null;
for (let y = 0; y < BOARD_ROWS; y++) {
for (let x = 0; x < BOARD_COLS; x++) {
const p = testBoard[y][x];
if (p && p.color === color && (p.type === '帅' || p.type === '将')) {
genPos = { x, y };
break;
}
}
if (genPos) break;
}
if (!genPos) return false;
const enemyColor = color === RED ? BLACK : RED;
for (let y = 0; y < BOARD_ROWS; y++) {
for (let x = 0; x < BOARD_COLS; x++) {
const p = testBoard[y][x];
if (p && p.color === enemyColor) {
// Temporarily set board for validation
const origBoard = board;
// We need a way to test moves without affecting global state
// Use a clone approach
if (canAttack(x, y, genPos.x, genPos.y, testBoard)) {
return true;
}
}
}
}
return false;
}
function canAttack(fromX, fromY, toX, toY, testBoard) {
const piece = testBoard[fromY][fromX];
if (!piece) return false;
const target = testBoard[toY][toX];
if (target && target.color === piece.color) return false;
const dx = toX - fromX;
const dy = toY - fromY;
const adx = Math.abs(dx);
const ady = Math.abs(dy);
switch (piece.type) {
case '帅':
case '将':
if (adx > 1 || ady > 1 || adx + ady !== 1) return false;
if (toX < 3 || toX > 5) return false;
if (piece.color === RED && toY < 7) return false;
if (piece.color === BLACK && toY > 2) return false;
break;
case '仕':
case '士':
if (adx !== 1 || ady !== 1) return false;
if (toX < 3 || toX > 5) return false;
if (piece.color === RED && toY < 7) return false;
if (piece.color === BLACK && toY > 2) return false;
break;
case '相':
case '象':
if (adx !== 2 || ady !== 2) return false;
if (testBoard[fromY + dy/2][fromX + dx/2]) return false;
if (piece.color === RED && toY < 5) return false;
if (piece.color === BLACK && toY > 4) return false;
break;
case '马':
if (!((adx === 1 && ady === 2) || (adx === 2 && ady === 1))) return false;
if (adx === 2) {
if (testBoard[fromY][fromX + dx/2]) return false;
} else {
if (testBoard[fromY + dy/2][fromX]) return false;
}
break;
case '车':
if (dx !== 0 && dy !== 0) return false;
if (dx === 0) {
const step = dy > 0 ? 1 : -1;
for (let y = fromY + step; y !== toY; y += step) {
if (testBoard[y][fromX]) return false;
}
} else {
const step = dx > 0 ? 1 : -1;
for (let x = fromX + step; x !== toX; x += step) {
if (testBoard[fromY][x]) return false;
}
}
break;
case '炮':
if (dx !== 0 && dy !== 0) return false;
let obstacles = 0;
if (dx === 0) {
const step = dy > 0 ? 1 : -1;
for (let y = fromY + step; y !== toY; y += step) {
if (testBoard[y][fromX]) obstacles++;
}
} else {
const step = dx > 0 ? 1 : -1;
for (let x = fromX + step; x !== toX; x += step) {
if (testBoard[fromY][x]) obstacles++;
}
}
if (target) {
if (obstacles !== 1) return false;
} else {
if (obstacles !== 0) return false;
}
break;
case '兵':
case '卒':
if (adx + ady !== 1) return false;
const crossed = (piece.color === RED && fromY <= 4) || (piece.color === BLACK && fromY >= 5);
if (!crossed) {
if (piece.color === RED && dy !== -1) return false;
if (piece.color === BLACK && dy !== 1) return false;
if (dx !== 0) return false;
} else {
if (piece.color === RED && dy === 1) return false;
if (piece.color === BLACK && dy === -1) return false;
}
break;
}
return true;
}
function wouldBeInCheck(fromX, fromY, toX, toY, color) {
const temp = board.map(row => [...row]);
const piece = temp[fromY][fromX];
temp[toY][toX] = { ...piece, x: toX, y: toY };
temp[fromY][fromX] = null;
return isInCheck(color, temp);
}
function getAllLegalMoves(color) {
const moves = [];
for (let y = 0; y < BOARD_ROWS; y++) {
for (let x = 0; x < BOARD_COLS; x++) {
const piece = board[y][x];
if (piece && piece.color === color) {
for (let ty = 0; ty < BOARD_ROWS; ty++) {
for (let tx = 0; tx < BOARD_COLS; tx++) {
if (x === tx && y === ty) continue;
if (isLegalMove(x, y, tx, ty)) {
if (!wouldBeInCheck(x, y, tx, ty, color)) {
moves.push({ from: { x, y }, to: { x: tx, y: ty }, piece: piece.type });
}
}
}
}
}
}
}
return moves;
}
function isCheckmate(color) {
return isInCheck(color) && getAllLegalMoves(color).length === 0;
}
function isStalemate(color) {
return !isInCheck(color) && getAllLegalMoves(color).length === 0;
}
// ==================== MOVE EXECUTION ====================
function makeMove(fromX, fromY, toX, toY) {
const piece = board[fromY][fromX];
const captured = board[toY][toX];
board[toY][toX] = { ...piece, x: toX, y: toY };
board[fromY][fromX] = null;
lastMove = { from: { x: fromX, y: fromY }, to: { x: toX, y: toY } };
// Check for game end
const nextColor = currentPlayer === RED ? BLACK : RED;
if (isCheckmate(nextColor)) {
gameOver = true;
showMessage(`${currentPlayer === RED ? '红方' : '黑方'} 胜利!`);
} else if (isStalemate(nextColor)) {
gameOver = true;
showMessage('和棋!');
}
currentPlayer = nextColor;
updateStatus();
drawGame();
if (!gameOver && currentPlayer === BLACK) {
isAITurn = true;
setTimeout(makeAIMove, 500);
} else {
isAITurn = false;
}
}
function showMessage(text) {
messageOverlay.textContent = text;
messageOverlay.style.display = 'block';
setTimeout(() => {
messageOverlay.style.display = 'none';
}, 3000);
}
function updateStatus() {
turnPiece.className = `turn-piece ${currentPlayer}`;
turnText.textContent = currentPlayer === RED ? '红方' : '黑方';
}
// ==================== AI ====================
const PIECE_VALUES = {
'帅': 10000, '将': 10000,
'仕': 200, '士': 200,
'相': 200, '象': 200,
'马': 450, '车': 450,
'车': 900,
'炮': 450,
'兵': 100, '卒': 100
};
const POSITION_BONUS = {
'兵': [
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[20,20,30,30,40,30,30,20,20],
[30,40,50,60,70,60,50,40,30],
[50,60,80,90,100,90,80,60,50],
[0,0,0,0,0,0,0,0,0]
],
'卒': [
[0,0,评分结论
按「质量 70% + 性能 30%」加权,本场最佳:DeepSeek(综合分 8.2)。
常见问题
- 这份报告对比了哪些 AI 产品?
- 本次同题横评覆盖:智谱清言、Kimi、DeepSeek 对话、通义千问。同一任务、同一提示词并发调用,逐项指标并列对比。
- 这份横评报告的核心结论是什么?
- 本报告由「AI 大众点评 · 同题横评工作台」自动生成,同一任务并发调用多家大模型后对比输出。
- 这份横评报告是如何产生的?
- 报告来自同题横评工作台:注册会员输入任务并勾选 2-4 家模型并发调用,记录输出质量、耗时、Token 消耗与费用,打分后一键发布。生成产物可在页面内在线试玩验证。
评论(0)
评论加载中…


