Skip to content

Commit

Permalink
add random for best score candicates
Browse files Browse the repository at this point in the history
  • Loading branch information
HuiGong-dev committed Jan 11, 2022
1 parent 3110918 commit f4ad166
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion app.js
Original file line number Diff line number Diff line change
Expand Up @@ -379,12 +379,16 @@ function minimaxNextMove(){
let currentPlayerMinimax = isCpuMaximizing? 'x' : 'o';
let bestScore = isCpuMaximizing? (-Infinity) : (+Infinity);
let move;
let scoreList = {};
for (let i = 0; i < 9; i++){
if(arrayForMinimax[i] === ''){
arrayForMinimax[i] = currentPlayerMinimax;
// next move is the player 1 not cpu, that's why !isCpuMaximizing
let score = minimax(0, !isCpuMaximizing);
arrayForMinimax[i] = '';
// store all score in a score list
scoreList[i] = score;
console.log("index:" + i + "score:" + score);
if (isCpuMaximizing){
if (score > bestScore) {
bestScore = score;
Expand All @@ -398,7 +402,12 @@ function minimaxNextMove(){
}
}
}
return cellElements[move];
// list of all best candidates (they all have the best score)
let finalCandidates = findKeysByValue(scoreList, bestScore);
console.log("the final candidates:" + finalCandidates)
let finalMove = randomNextMove(finalCandidates);
console.log("final move:" + finalMove);
return cellElements[finalMove];
}

let scores = {
Expand Down Expand Up @@ -440,6 +449,16 @@ function minimax(depth, isMaximizing) {
}
}

function findKeysByValue(map, score){
const keyList = [];
Object.keys(map).forEach(key => {
if (map[key] == score) {
keyList.push(key);
}
});
return keyList;
}

// check win based on minimax array
function checkWinForminimax(currentClassInminimax) {
return WINNING_PATTERNS.some(pattern => {
Expand Down

0 comments on commit f4ad166

Please sign in to comment.