【发布时间】:2021-12-21 12:38:16
【问题描述】:
我正在尝试编写一个简单的功能,其中我从 sqlite 数据库中检索 .pgn 并从 chessboard.js 加载棋盘,这允许用户通过按箭头键玩该游戏(左收回并有权进行下一步)。
我能够设置一个只允许legal moves 的板。
var board = null
var game = new Chess()
var $status = $('#status')
var $fen = $('#fen')
var $pgn = $('#pgn')
function onDragStart (source, piece, position, orientation) {
// do not pick up pieces if the game is over
if (game.game_over()) return false
// only pick up pieces for the side to move
if ((game.turn() === 'w' && piece.search(/^b/) !== -1) ||
(game.turn() === 'b' && piece.search(/^w/) !== -1)) {
return false
}
}
function onDrop (source, target) {
// see if the move is legal
var move = game.move({
from: source,
to: target,
promotion: 'q' // NOTE: always promote to a queen for example simplicity
})
// illegal move
if (move === null) return 'snapback'
updateStatus()
}
// update the board position after the piece snap
// for castling, en passant, pawn promotion
function onSnapEnd () {
board.position(game.fen())
}
function takeBack () {
board.position(game.undo())
}
function updateStatus () {
var status = ''
var moveColor = 'White'
if (game.turn() === 'b') {
moveColor = 'Black'
}
// checkmate?
if (game.in_checkmate()) {
status = 'Game over, ' + moveColor + ' is in checkmate.'
}
// draw?
else if (game.in_draw()) {
status = 'Game over, drawn position'
}
// game still on
else {
status = moveColor + ' to move'
// check?
if (game.in_check()) {
status += ', ' + moveColor + ' is in check'
}
}
$status.html(status)
$fen.html(game.fen())
$pgn.html(game.pgn())
}
var config = {
draggable: true,
position: 'start',
onDragStart: onDragStart,
onDrop: onDrop,
onSnapEnd: onSnapEnd
}
board = Chessboard('legalBoard', config)
updateStatus()
后面是下面的html代码。
<div id="legalBoard" style="width: 400px"></div>
<span>Status</span>
<div id="status"></div>
<span>PGN</span>
<div id="pgn"></div>
<span>FEN</span>
<div id="fen"></div>
它创建了以下棋盘,确实允许用户捡起棋子并进行合法移动:
我需要如何调整此代码以加载到游戏中,并允许用户按箭头键并玩该游戏?
【问题讨论】:
标签: javascript sqlite chessboard.js