Chess.js загружает собственный fen, но при переходе через pgn возвращается к fen по умолчанию, что приводит к остановке Javascript

Форум по Javascript
Ответить Пред. темаСлед. тема
Anonymous
 Chess.js загружает собственный fen, но при переходе через pgn возвращается к fen по умолчанию, что приводит к остановке

Сообщение Anonymous »

Извините, это может быть очень нубский вопрос.
Я создаю для кого-то базу данных шахматных pgn и застрял на финише.
У меня все работает (когда загружена стандартная шахматная нотация Форсайта-Эдвардса (FEN))
Каждый раз, когда я загружаю собственный фен из базы данных, он загружается нормально, но когда нажимаешь следующую кнопку, она откатывается назад на болото по умолчанию.
Скажите, пожалуйста, что я могу сделать, чтобы решить эту проблему.
ChatGPT тоже не знает
window.loadPGN = function(id) {
$.getJSON('php/get_pgn.php?id=' + id, function(data) {
if (data.success) {
const startingFen = data.starting_fen || 'start';

// Initialize the chessboard with the starting FEN
board = ChessBoard('annotation-board', {
pieceTheme: cfg.pieceTheme,
position: startingFen,
});

// Initialize the Chess.js game object with the starting FEN
game = new Chess(startingFen);

// Load the PGN into the Chess.js game instance
game.load_pgn(data.pgn_data);

// Display PGN and metadata
$('#move-window').html(data.pgn_data);

let metadata =
`Tournament: ${data.tournament || "N/A"}

Time Control: ${data.time_control || "N/A"}

Variant: ${data.variant || "N/A"}

White: ${data.white_player || "N/A"} (${data.white_elo || "N/A"})

Black: ${data.black_player || "N/A"} (${data.black_elo || "N/A"})

Result: ${data.result || "N/A"}

Termination: ${data.termination || "N/A"}

Date: ${data.date || "N/A"}

Starting FEN: ${startingFen}`;
$('#annotation-window').html(metadata);

// Reset move history and controls
moves = game.history({
verbose: true
});
currentMoveIndex = 0;

$('#nextBtn').on('click', function() {
if (currentMoveIndex < moves.length) {
const move = moves[currentMoveIndex]; // Get the next move
game.move(move); // Apply the move to the game
board.position(game.fen()); // Update the board with the new position
currentMoveIndex++;
} else {
console.log("No more moves.");
}
});

$('#prevBtn').on('click', function() {
if (currentMoveIndex > 0) {
game.undo(); // Undo the last move
board.position(game.fen()); // Update the board with the new position
currentMoveIndex--;
} else {
console.log("Already at the first move.");
}
});

$('#startPositionBtn').on('click', function() {
game.reset(); // Reset the game to its initial state
game.load(startingFen); // Reload the game with the starting FEN
board.position(startingFen); // Set the board to the starting FEN
currentMoveIndex = 0;
});

$('#endPositionBtn').on('click', function() {
while (currentMoveIndex < moves.length) {
const move = moves[currentMoveIndex];
game.move(move); // Apply the move
currentMoveIndex++;
}
board.position(game.fen()); // Update the board to the final position
});
} else {
console.error("Failed to fetch PGN:", data.message);
}
});
};

Я перепробовал очень много разных вещей.
Последнее, что я пробовал, — это внедрить собственный fen в файл Chess.js
var DEFAULT_POSITION = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1';

// Allow injection of a custom FEN for game initialization
window.setCustomFEN = function(fen) {
DEFAULT_POSITION = fen;
};

и обновите нагрузку в index.html
window.loadPGN = function(id) {
$.getJSON('php/get_pgn.php?id=' + id, function(data) {
if (data.success) {
setCustomFEN(data.starting_fen); // ✅ Injecting the custom FEN
game = new Chess(DEFAULT_POSITION); // ✅ Using the overridden FEN
board.position(DEFAULT_POSITION);
game.load_pgn(data.pgn_data);
moves = game.history({
verbose: true
});
currentMoveIndex = 0;
$('#move-window').html(data.pgn_data);
}
});
};


Подробнее здесь: https://stackoverflow.com/questions/793 ... ugh-pgn-th
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Javascript»