minmaxalgo
minmaxalgo
import numpy as np
import sys
ROWS = 6
COLUMNS = 7
PLAYER1 = 1
PLAYER2 = 2
class ConnectFour:
def __init__(self):
self.board = np.zeros((ROWS, COLUMNS), int)
def print_board(self):
print(np.flip(self.board, 0))
return False
if depth == 0 or is_terminal:
if self.winning_move(PLAYER1):
return (None, 100000000000000)
elif self.winning_move(PLAYER2):
return (None, -10000000000000)
else:
return (None, 0)
if maximizing_player:
value = -np.inf
column = np.random.choice(valid_locations)
for col in valid_locations:
row = self.get_next_open_row(col)
self.drop_piece(row, col, PLAYER1)
new_score = self.minimax(depth - 1, alpha, beta, False)[1]
self.drop_piece(row, col, 0)
if new_score > value:
value = new_score
column = col
alpha = max(alpha, value)
if alpha >= beta:
break
return column, value
else:
value = np.inf
column = np.random.choice(valid_locations)
for col in valid_locations:
row = self.get_next_open_row(col)
self.drop_piece(row, col, PLAYER2)
new_score = self.minimax(depth - 1, alpha, beta, True)[1]
self.drop_piece(row, col, 0)
if new_score < value:
value = new_score
column = col
beta = min(beta, value)
if beta <= alpha:
break
return column, value
def play_game(self):
while True:
# Player 1 Input
self.print_board()
col = int(input("Player 1 (1) - Select a column (0-6): "))
if self.is_valid_location(col):
row = self.get_next_open_row(col)
self.drop_piece(row, col, PLAYER1)
if self.winning_move(PLAYER1):
self.print_board()
print("Player 1 wins!")
break
if self.winning_move(PLAYER2):
self.print_board()
print("Player 2 (AI) wins!")
break
if __name__ == "__main__":
game = ConnectFour()
game.play_game()