【问题标题】:Using Chessboard.js to load in pgn and allow users to play through the game with arrow key presses使用 Chessboard.js 加载 pgn 并允许用户按箭头键玩游戏
【发布时间】: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


    【解决方案1】:
    1. 使用 @mliebelt/pgn-parser 解析 pgn
      1.1 import { parse } from '@mliebelt/pgn-parser'
      1.2let moves = parse(my_pgn_string, {startRule: "game"}).moves;
    2. 循环移动
    3. 使用 Chess 对象将 PGN 符号转换为开始和结束移动:
      3.1let move_obj = game.move(moves[i].notation.notation);
    4. 使用棋盘移动显示移动:
      4.1chessboard.move(move_obj.from +'-'+ move_obj.to);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-08
      • 1970-01-01
      • 2015-04-14
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多