Build Your Own Connect Four AI
Hi,
I just finished the last project of Learn the Basics of Machine Learning course.
The codecademy_evaluate_board()
function a bit hard to interpreted.
I had another idea how to create same (or maybe better AI).
My AI vs. CodeCademy AI is win with depth 3/4 tuning too… I am so proud…
Please take a look to my evaluation function:
Summary
def improved_evaluate_board(board):
board = np.array(board)
def check_streak(player, row):
#check triple streak
double = player * 2
triple = player * 3
if f" {triple}" in row or f"{triple} " in row or f"{player} {double}" in row or f"{double} {player}" in row:
return 2
#check double streak
if f" {double}" in row or f" {double} " in row or f"{double} " in row or f"{player} {player} " in row or f" {player} {player}" in row:
#print(f"{double} streak found")
return 1
return 0
def get_all_way(arr2d):
max_col = len(arr2d[0])
max_row = len(arr2d)
cols = [[] for _ in range(max_col)]
rows = [[] for _ in range(max_row)]
fdiag = [[] for _ in range(max_row + max_col - 1)]
bdiag = [[] for _ in range(len(fdiag))]
min_bdiag = -max_row + 1
for x in range(max_col):
for y in range(max_row):
cols[x].append(arr2d[y][x])
rows[y].append(arr2d[y][x])
fdiag[x+y].append(arr2d[y][x])
bdiag[x-y-min_bdiag].append(arr2d[y][x])
return cols, rows, fdiag, bdiag
def counter(arr, x_streak, o_streak):
if len(arr) < 4:
return x_streak, o_streak
for row in arr:
row = "".join(row)
x_streak += check_streak("X", row)
o_streak += check_streak("O", row)
return x_streak, o_streak
if has_won(board, "X"):
return float("Inf")
if has_won(board, "O"):
return -float("Inf")
rows, cols, fdiag, bdiag = get_all_way(board)
x_streak, o_streak = counter(rows, 0, 0)
x_streak, o_streak = counter(cols, x_streak, o_streak)
x_streak, o_streak = counter(fdiag, x_streak, o_streak)
x_streak, o_streak = counter(bdiag, x_streak, o_streak)
return x_streak - o_streak
The full code you can found here:
Link to Repl
Link to GitHub