Đây là một ví dụ về cách viết thuật toán Monte Carlo Tree Search (MTCS) để chơi trò chơi Tic Tac Toe bằng JavaScript:
// Hàm để tạo trạng thái tích cực mới (vị trí độc quyền từ giá trị max)
function createPositiveState() {
let newState = [
['O', '-', '-'],
['-', 'O', '-'],
['-', '-', '-']
];
return newState;
}
// Hàm để tạo trạng thái tiêu cực mới (vị trí độc quyền từ giá trị min)
function createNegativeState() {
let newState = [
['X', '-', '-'],
['-', 'X', '-'],
['-', '-', '-']
];
return newState;
}
// Hàm để tạo trạng thái ban đầu
function createInitialState() {
let newState = [
['-', '-', '-'],
['-', '-', '-'],
['-', '-', '-']
];
return newState;
}
// Hàm để kiểm tra xem trạng thái đã kết thúc chưa (trò chơi đã kết thúc)
function isTerminalState(state) {
// Kiểm tra các cột
for (let i = 0; i < 3; i++) {
if (state[i][0] !== '-' && state[i][0] === state[i][1] && state[i][1] === state[i][2]) {
return true;
}
}
// Kiểm tra các hàng
for (let i = 0; i < 3; i++) {
if (state[0][i] !== '-' && state[0][i] === state[1][i] && state[1][i] === state[2][i]) {
return true;
}
}
// Kiểm tra theo đường chéo
if (state[0][0] !== '-' && state[0][0] === state[1][1] && state[1][1] === state[2][2]) {
return true;
}
if (state[0][2] !== '-' && state[0][2] === state[1][1] && state[1][1] === state[2][0]) {
return true;
}
// Kiểm tra tất cả các vị trí đã được đánh dấu (tiêu trí hòa)
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (state[i][j] == '-') {
// Trò chơi chưa kết thúc
return false;
}
}
}
// Trò chơi hòa
return true;
}
// Hàm để sao chép một trạng thái mới
function copyState(state) {
let newState = [];
for (let i = 0; i < state.length; i++) {
newState.push([...state[i]]);
}
return newState;
}
// Class Node biểu diễn một node của cây
class Node {
constructor(state, player) {
this.state = copyState(state);
this.player = player;
this.wins = 0;
this.visits = 0;
this.children = [];
}
// Chọn một trẻ em ngẫu nhiên và bỏ qua trlực tiếp
selectChild() {
let unexplored = [];
for (let i = 0; i < this.children.length; i++) {
if (this.children[i].visits === 0) {
unexplored.push(this.children[i]);
}
}
// Nếu có bất kỳ nút chưa thử nghiệm nào, trả về ngẫu nhiên trong số đó
if (unexplored.length > 0) {
let idx = Math.floor(Math.random() * unexplored.length);
return unexplored[idx];
}
// Nếu không, sử dụng công thức UCB để chọn một nút
// UCB1 Formula: winRate = wins / visits, exploitation = sqrt(log(totalVisits) / visits), exploration = C * exploitation
let C = 1.4;
let totalVisits = this.visits;
let selectedChild = this.children[0];
let bestValue = -Infinity;
for (let i = 0; i < this.children.length; i++) {
let child = this.children[i];
let exploitValue = child.wins / child.visits;
let exploreValue = C * Math.sqrt(Math.log(totalVisits) / child.visits);
let ucbValue = exploitValue + exploreValue;
if (ucbValue > bestValue) {
selectedChild = child;
bestValue = ucbValue;
}
}
return selectedChild;
}
// Thêm một nút mới là con của nút hiện tại
addChild(childState) {
let childPlayer = this.player === 'X' ? 'O' : 'X';
let childNode = new Node(childState, childPlayer);
this.children.push(childNode);
return childNode;
}
// Cập nhật kết quả của nút
update(winner) {
if (winner === this.player) {
this.wins += 1;
}
this.visits += 1;
}
// Mô tả node này
toString() {
let strState = '';
for (let i = 0; i < this.state.length; i++) {
for (let j = 0; j < this.state[i].length; j++) {
strState += ${this.state[i][j]}\t;
}
strState += '\n';
}
return ${strState} Player: ${this.player}, Wins/Visits: ${this.wins}/${this.visits};
}
}
// Class Monte Carlo Tree Search
class MTCS {
constructor(rootNode) {
this.rootNode = rootNode;
}
// Tìm kiếm một vị trí tốt nhất cho người chơi hiện tại và trả về tham chiếu của nút tương ứng
findBestMove(numIterations) {
for (let i = 0; i < numIterations; i++) {
let node = this.selectNode();
let winner = this.playout(node);
this.backpropagate(node, winner);
}
// Tìm vị trí tốt nhất
let bestChild;
let bestValue = -Infinity;
for (let i = 0; i < this.rootNode.children.length; i++) {
let child = this.rootNode.children[i];
let childValue = child.wins / child.visits;
if (childValue > bestValue) {
bestChild = child;
bestValue = childValue;
}
}
return bestChild;
}
// Chọn một nút để thực hiện Monte Carlo Tree Search
selectNode() {
let currentNode = this.rootNode;
while (currentNode.children.length > 0) {
currentNode = currentNode.selectChild();
}
return currentNode;
}
// Thực hiện ván chơi từ nút được chọn đến hoàn thành ván đấu
playout(node) {
let currentState = node.state;
let currentPlayer = node.player;
while (!isTerminalState(currentState)) {
// Chọn một vị trí ngẫu nhiên để đánh
let possibleMoves = [];
for (let i = 0; i < currentState.length; i++) {
for (let j = 0; j < currentState[i].length; j++) {
if (currentState[i][j] === '-') {
possibleMoves.push([i, j]);
}
}
}
let move = possibleMoves[Math.floor(Math.random() * possibleMoves.length)];
// Đánh dấu vị trí được chọn
currentState[move[0]][move[1]] = currentPlayer;
// Chuyển lượt chơi
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
}
// Trả về người chơi winnned or null nếu hòa
if (isTerminalState(currentState)) {
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (currentState[i][j] != '-') {
return currentState[i][j];
}
}
}
}
// Hòa
return null;
}
// Cập nhật lại thông tin của các nút trên đường đi từ nút được chọn đến nút gốc
backpropagate(node, winner) {
while (node !== null) {
node.update(winner);
node = node.parent;
}
}
}
// Tạo các trạng thái mới cho các tình huống tích cực và tiêu cực
let positiveState = createPositiveState();
let negativeState = createNegativeState();
// Tạo trạng thái ban đầu và thực hiện Monte Carlo Tree Search để tìm vị trí tốt nhất cho người chơi hiện tại
let initialState = createInitialState();
let rootNode = new Node(initialState, 'X');
let mtcs = new MTCS(rootNode);
let bestNode = mtcs.findBestMove(1000);
// In thông tin trạng thái và nút tốt nhất tìm thấy
console.log('\nInitial State:');
console.log(rootNode.toString());
console.log('\nBest State:');
console.log(bestNode.toString());