Skip to content

Commit 1cdc322

Browse files
committed
commit ABPruning + MinMax
1 parent f1cfed0 commit 1cdc322

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

game_search_algo.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import math,numpy as np
2+
# Alpha - Beta Pruning
3+
# some upper and lower bounds
4+
MAX=np.inf
5+
MIN=-np.inf
6+
# define game-state array here
7+
arr=[8,7,3,9,9,8,2,4,1,8,8,9,9,9,3,4 ]
8+
# lim Finds the number of levels to recur.
9+
lim=math.log(len(arr),2)
10+
11+
# AB Pruning is a wrapper to the min max algorithm that cuts the search tree by saving compute time..
12+
def Alpha_Beta_Pruning(state_arr,index,depth,ismaxnode,alpha,beta):
13+
if(depth==lim):
14+
return state_arr[index]
15+
if(ismaxnode):
16+
best=MIN
17+
for i in range(2):
18+
val=Alpha_Beta_Pruning(state_arr,index*2+i,depth+1,False,alpha,beta)
19+
best=max(best,val)
20+
alpha=max(alpha,best)
21+
if(alpha>=beta):
22+
print(f"Pruned at depth :{depth+1}")
23+
break
24+
return best
25+
else:
26+
best=MAX
27+
for i in range(2):
28+
val=Alpha_Beta_Pruning(state_arr,index*2+i,depth+1,True,alpha,beta)
29+
best=min(best,val)
30+
beta=min(beta,best)
31+
if(alpha>=beta):
32+
print(f"Pruned at depth :{depth+1}")
33+
break
34+
return best
35+
36+
'''
37+
Min max
38+
'''
39+
#Min max is the base algorithm for alpha beta pruning so the code base has less changes .
40+
41+
def minmax(state_arr,index,depth,ismaxnode):
42+
if(depth==lim):
43+
return state_arr[index]
44+
if(ismaxnode):
45+
best=MIN
46+
for i in range(2):
47+
val=minmax(state_arr,index*2+i,depth+1,False)
48+
best=max(best,val)
49+
return best
50+
else:
51+
best=MAX
52+
for i in range(2):
53+
val=minmax(state_arr,index*2+i,depth+1,True)
54+
best=min(best,val)
55+
return best
56+
57+
58+
print("Alpha Beta Pruning:",Alpha_Beta_Pruning(arr,0,0,True,MIN,MAX))
59+
print("Min-Max Algorithm :",minmax(arr,0,0,True))

0 commit comments

Comments
 (0)