-
Notifications
You must be signed in to change notification settings - Fork 2
/
calculate-cpu.js
62 lines (53 loc) · 1.5 KB
/
calculate-cpu.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const getRandomElement = array => {
return array[Math.floor(Math.random()*array.length)];
}
const clone = o => {
return JSON.parse(JSON.stringify(o));
}
const normalizeKeys = states => {
const keys = Object.keys(states).sort((a, b) => a - b);
const newStates = {};
keys.forEach(key => {
let state = newStates[keys.indexOf(key)] = states[key];
Object.keys(state.moves).forEach(index => {
const newKey = keys.indexOf(state.moves[index] + "");
state.moves[index] = newKey;
});
})
return newStates;
}
const calculateCPU = (states, cpuPlayer) => {
const newStatesHash = {};
const newStates = [];
const addState = state => {
state = clone(state);
newStatesHash[state.key] = state;
newStates.push(state);
}
const processState = state => {
Object.keys(state.moves).forEach(index => {
const cpuMove = findCpuMove(
states[state.moves[index]]
);
addState(cpuMove);
state.moves[index] = cpuMove.key;
});
}
const findCpuMove = state => {
if(state.player != cpuPlayer){
return state;
}
const children = Object.keys(state.moves).map(i => states[state.moves[i]]);
return children.find(child => child.result == cpuPlayer) ||
children.find(child => child.result == "tie") ||
getRandomElement(children) ||
state;
}
addState(findCpuMove(states[0]));
let i = 0;
while(i < newStates.length){
processState(newStates[i++]);
}
return normalizeKeys(newStatesHash);
}
module.exports = calculateCPU;