@andreabiagini5/applicazioni-e-servizi-web-project
Version:
Project for Applicazioni e Servizi Web.
62 lines • 1.97 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getMove = void 0;
const Move_1 = require("../models/Move");
const prolog_1 = require("../prolog/prolog");
const getMove = async (board) => {
const parsedBoard = parseBoard(board);
const goal = `best_move(${parsedBoard}, Best).`;
let result;
try {
result = await (0, prolog_1.query)(goal);
}
catch (error) {
console.error('Error in Prolog engine:', error);
return undefined;
}
if (!result || result.length === 0) {
console.error('No results from Prolog');
return undefined;
}
const move = result[0];
try {
return parseMove(move);
}
catch (error) {
console.error('Error parsing move result:', error);
return undefined;
}
};
exports.getMove = getMove;
// TODO | Randa: Here I am manually inverting coordinates, maybe there's a better way to do it.
const parseMove = (move) => {
// The move format is 'Best = cell(2,2)'"
const regex = /^Best = cell\((\d+),(\d+)\)$/;
const match = move.match(regex);
if (!match) {
throw new Error('Invalid move format');
}
const x = parseInt(match[1], 10);
const y = parseInt(match[2], 10);
if (isNaN(x) || isNaN(y)) {
throw new Error('Invalid move coordinates');
}
return Move_1.MoveFactory.create(y, x);
};
const parseBoard = (Board) => {
const height = Board.height;
const width = Board.width;
const cells = Board.state;
const cellList = cells
.flatMap((row, rowIndex) => row.flatMap((cell, colIndex) => {
if (!cell.pile)
return [];
const owner = cell.pile.owner;
return [
`cell(${colIndex}, ${rowIndex}, ${owner === 'bot' ? 'me' : 'opponent'}, ${cell.pile.numberOfGrains})`,
];
}))
.join(', ');
return `board(${width}, ${height}, [${cellList}])`;
};
//# sourceMappingURL=bot.js.map