-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathjsTree.js
83 lines (75 loc) · 2.07 KB
/
jsTree.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const INFINITY = 99999; // Put a large number in here.
// Function to get a tree of desired depth and leaves
function jsTree(depth, leaves) {
var node = new Object();
node.value = 0;
node.status = 0;
node.terminal = function(){return false;};
node.children = new Array;
if(depth > 0){
for(var i = leaves; i > 0; i--){
node.children.push(jsTree(depth-1, leaves));
}
}
if(depth==0) {node.value=Math.round(9 * Math.random(6))}
return node;
}
// Function to display the tree in the HTML page.
function displayTree(node){
var str = "";
function createTreeHTML(node){
str = str + "<div><p class='status-" + node.status+ "'>" + node.value + "</p>";
for(var child in node.children){
createTreeHTML(node.children[child]);
}
str = str + "</div>";
}
createTreeHTML(node);
$('#tree-container').html(str);
}
// Evaluation function
function evaluate(node){
return (DEPTH%2 ? -1: 1) * node.value;
}
// Clear the colours in the HTML display
function resetStatus(node, depth, status){
node.status = status;
if((node.terminal)() == true || depth == 0)
return;
for(var child in node.children){
resetStatus(node.children[child], depth-1, status);
}
}
// Give new random values to the leaf nodes and set all other nodes values to 0
function resetValues(node, depth){
node.value = 0;
if((node.terminal)() == true || depth == 0)
node.value = Math.round(9 * Math.random(6));
for(var child in node.children){
resetValues(node.children[child], depth-1);
}
}
// Minimax algorithm
function minimax(node, depth){
node.status = 1;
if((node.terminal)() == true || depth == 0)
return evaluate(node);
a = -INFINITY;
for(var child in node.children){
a = Math.max(a, -minimax(node.children[child], depth-1));
}
node.value = a;
return a;
}
// AlphaBeta algorithm
function alphabeta(node, depth, alpha, beta){
node.status = 1;
if((node.terminal)() == true || depth == 0)
return evaluate(node);
for(var child in node.children){
alpha = Math.max(alpha, -alphabeta(node.children[child], depth-1, -beta, -alpha));
node.value = alpha;
if(beta <= alpha){break;}
}
return alpha;
}