mirror of
https://github.com/kuhyx/WUT_Computer_Science.git
synced 2026-11-19 13:34:28 +01:00
feat: set up alpha beta
This commit is contained in:
parent
108121a4ed
commit
d4cb446264
362
lab2/main.py
362
lab2/main.py
@ -1,4 +1,5 @@
|
|||||||
import re
|
import re
|
||||||
|
import copy
|
||||||
"""
|
"""
|
||||||
Program that plays draughts (checkers) with user on 8x8 board using min-max with alpha-beta prunning
|
Program that plays draughts (checkers) with user on 8x8 board using min-max with alpha-beta prunning
|
||||||
"""
|
"""
|
||||||
@ -11,8 +12,6 @@ class Game:
|
|||||||
self.board_size = size
|
self.board_size = size
|
||||||
self.white_positions = self.initialize_white()
|
self.white_positions = self.initialize_white()
|
||||||
self.black_positions = self.initialize_black()
|
self.black_positions = self.initialize_black()
|
||||||
# print(self.white_positions)
|
|
||||||
# print(self.black_positions)
|
|
||||||
|
|
||||||
def initialize_white(self):
|
def initialize_white(self):
|
||||||
"""Initialize white pieces"""
|
"""Initialize white pieces"""
|
||||||
@ -45,14 +44,14 @@ class Game:
|
|||||||
return black_positions
|
return black_positions
|
||||||
|
|
||||||
def check_move_out_of_bounds(self, from_, to):
|
def check_move_out_of_bounds(self, from_, to):
|
||||||
"""Check if the move destination is out of the bounds of the board"""
|
"""Check if the move destination is out of the bounds of the board"""
|
||||||
if to[0] < 0 or to[0] >= self.board_size - 1:
|
if to[0] < 0 or to[0] > self.board_size - 1:
|
||||||
print(f"Illegal move! Final x coordinate must be between 0 and {self.board_size}!")
|
# print(f"Illegal move! Final x coordinate must be between 0 and {self.board_size-1}!")
|
||||||
return True
|
return True
|
||||||
if to[1] < 0 or to[1] >= self.board_size - 1:
|
if to[1] < 0 or to[1] > self.board_size - 1:
|
||||||
print(f"Illegal move! Final y coordinate must be between 0 and {self.board_size}!")
|
# print(f"Illegal move! Final y coordinate must be between 0 and {self.board_size-1}!")
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def check_piece_exists(self, coords, color):
|
def check_piece_exists(self, coords, color):
|
||||||
"""Check if a piece of given color exists at a given spot"""
|
"""Check if a piece of given color exists at a given spot"""
|
||||||
@ -90,7 +89,7 @@ class Game:
|
|||||||
if (abs(to[0]-from_[0]) != 2 or abs(to[1]-from_[1] != 2)):
|
if (abs(to[0]-from_[0]) != 2 or abs(to[1]-from_[1] != 2)):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
middle = (abs(to[0]-from_[0])//2, abs(to[1]-from_[1])//2)
|
middle = (abs(to[0]+from_[0])//2, abs(to[1]+from_[1])//2)
|
||||||
|
|
||||||
if color == "white" and self.check_piece_exists(middle, "black"):
|
if color == "white" and self.check_piece_exists(middle, "black"):
|
||||||
return middle
|
return middle
|
||||||
@ -101,21 +100,29 @@ class Game:
|
|||||||
def check_move_legal(self, from_, to, color):
|
def check_move_legal(self, from_, to, color):
|
||||||
"""Check if a move is legal. Return a boolean or coordinates of captured piece"""
|
"""Check if a move is legal. Return a boolean or coordinates of captured piece"""
|
||||||
if self.check_move_out_of_bounds(from_, to):
|
if self.check_move_out_of_bounds(from_, to):
|
||||||
print("Illegal move! Final position is out of the bounds of the board")
|
if from_ == (2, 3):
|
||||||
|
print(f"To: {to}")
|
||||||
|
print("Illegal move! Final position is out of the bounds of the board")
|
||||||
return False
|
return False
|
||||||
if not self.check_piece_exists(from_, color):
|
if not self.check_piece_exists(from_, color):
|
||||||
print(
|
if from_ == (2, 3):
|
||||||
"Illegal move! There is no piece on the starting position that belongs to the player")
|
print(f"To: {to}")
|
||||||
|
print(
|
||||||
|
"Illegal move! There is no piece on the starting position that belongs to the player")
|
||||||
return False
|
return False
|
||||||
if self.check_piece_exists(to, "white") or self.check_piece_exists(to, "black"):
|
if self.check_piece_exists(to, "white") or self.check_piece_exists(to, "black"):
|
||||||
print("Illegal move! Cannot move to position taken by another piece")
|
if from_ == (2, 3):
|
||||||
|
print(f"To: {to}")
|
||||||
|
print("Illegal move! Cannot move to position taken by another piece")
|
||||||
return False
|
return False
|
||||||
capture = self.check_capture(from_, to, color)
|
capture = self.check_capture(from_, to, color)
|
||||||
if capture == None:
|
if capture == None:
|
||||||
if self.check_move_piece_capable(from_, to, color):
|
if self.check_move_piece_capable(from_, to, color):
|
||||||
return True
|
return True
|
||||||
else:
|
else:
|
||||||
print('Illegal move!')
|
if from_ == (2, 3):
|
||||||
|
print(f"To: {to}")
|
||||||
|
print('Illegal move!')
|
||||||
return False
|
return False
|
||||||
return capture
|
return capture
|
||||||
|
|
||||||
@ -143,163 +150,186 @@ class Game:
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
def print_board(self):
|
def print_board(self):
|
||||||
"""Print the board in the console"""
|
"""Print the board in the console"""
|
||||||
print(" ", end="")
|
print(" ", end="")
|
||||||
for x in range(self.board_size):
|
|
||||||
print(f" {chr(ord('a')+x)} ", end="")
|
|
||||||
print(" ")
|
|
||||||
line = 0
|
|
||||||
for y in range(self.board_size*4):
|
|
||||||
for x in range(self.board_size):
|
for x in range(self.board_size):
|
||||||
bg = "#" if x%2==(y//4)%2 else " "
|
print(f" {chr(ord('a')+x)} ", end="")
|
||||||
checker = bg
|
print(" ")
|
||||||
if((x, y//4, False) in self.white_positions):
|
line = 0
|
||||||
checker = "w"
|
for y in range(self.board_size*4):
|
||||||
elif((x, y//4, True) in self.white_positions):
|
for x in range(self.board_size):
|
||||||
checker = "W"
|
bg = "#" if x % 2 == (y//4) % 2 else " "
|
||||||
elif((x, y//4, False) in self.black_positions):
|
checker = bg
|
||||||
checker = "b"
|
if ((x, y//4, False) in self.white_positions):
|
||||||
elif((x, y//4, True) in self.black_positions):
|
checker = "w"
|
||||||
checker = "B"
|
elif ((x, y//4, True) in self.white_positions):
|
||||||
|
checker = "W"
|
||||||
|
elif ((x, y//4, False) in self.black_positions):
|
||||||
|
checker = "b"
|
||||||
|
elif ((x, y//4, True) in self.black_positions):
|
||||||
|
checker = "B"
|
||||||
|
|
||||||
if(x==0):
|
if (x == 0):
|
||||||
if(line%4==2):
|
if (line % 4 == 2):
|
||||||
print('{:3d}'.format(y//4), end="")
|
print('{:3d}'.format(y//4), end="")
|
||||||
|
else:
|
||||||
|
print(" ", end="")
|
||||||
|
|
||||||
|
match line % 4:
|
||||||
|
case 0:
|
||||||
|
print("+---", end="")
|
||||||
|
case 1 | 3:
|
||||||
|
print(f"|{3*bg}", end="")
|
||||||
|
case 2:
|
||||||
|
print(f"|{bg}{checker}{bg}", end="")
|
||||||
|
if (line % 4 == 0):
|
||||||
|
print("+")
|
||||||
else:
|
else:
|
||||||
print(" ", end="")
|
print(f"|{y//4}" if line % 4 == 2 else "|")
|
||||||
|
line += 1
|
||||||
match line%4:
|
print(" ", end="")
|
||||||
case 0:
|
for x in range(self.board_size):
|
||||||
print("+---", end="")
|
print("+---", end="")
|
||||||
case 1 | 3:
|
print("+\n ", end="")
|
||||||
print(f"|{3*bg}", end="")
|
for x in range(self.board_size):
|
||||||
case 2:
|
print(f" {chr(ord('a')+x)}", end=" ")
|
||||||
print(f"|{bg}{checker}{bg}", end="")
|
print()
|
||||||
if(line%4==0):
|
|
||||||
print("+")
|
|
||||||
else:
|
|
||||||
print(f"|{y//4}" if line%4==2 else "|")
|
|
||||||
line+=1
|
|
||||||
print(" ", end="")
|
|
||||||
for x in range(self.board_size):
|
|
||||||
print("+---", end="")
|
|
||||||
print("+\n ", end="")
|
|
||||||
for x in range(self.board_size):
|
|
||||||
print(f" {chr(ord('a')+x)}", end=" ")
|
|
||||||
print()
|
|
||||||
|
|
||||||
# Ran first in the code
|
|
||||||
def get_possible_move_down(self, from_, color):
|
|
||||||
# all moves "down":
|
|
||||||
legal_moves = []
|
|
||||||
move_down_left_two = (from_[0] + 2, from_[1] - 2)
|
|
||||||
move_down_right_two = (from_[0] + 2, from_[1] + 2)
|
|
||||||
move_down_left_one = (from_[0] + 1, from_[1] - 1)
|
|
||||||
move_down_right_one = (from_[0] + 1, from_[1] + 1)
|
|
||||||
if self.check_move_legal(from_, move_down_left_two, color) != False:
|
|
||||||
legal_moves.append((from_, move_down_two))
|
|
||||||
elif self.check_move_legal(from_, move_down_right_two, color) != False:
|
|
||||||
legal_moves.append((from_, move_down_right_two))
|
|
||||||
elif self.check_move_legal(from_, move_down_left_one, color) != False:
|
|
||||||
legal_moves.append((from_, move_down_left_one))
|
|
||||||
elif self.check_move_legal(from_, move_down_right_one, color) != False:
|
|
||||||
legal_moves.append((from_, move_down_right_one))
|
|
||||||
return legal_moves
|
|
||||||
|
|
||||||
def get_possible_move(self, from_, color):
|
# Ran first in the code
|
||||||
# get all possible moves from the pawn in from_ position
|
def get_possible_move_capture(self, from_, color):
|
||||||
# "-" in first position -> move to the "left"
|
print(f"Checking piece {from_}")
|
||||||
# "+" in first postiin -> move to the "right"
|
# all capturing moves:
|
||||||
# "-" in second postion -> move "up"
|
legal_moves = []
|
||||||
# "+" in second position -> move "down"
|
move_down_left_two = (from_[0] + 2, from_[1] - 2)
|
||||||
legal_moves = self.get_possible_move_up(from_, color)
|
move_down_right_two = (from_[0] + 2, from_[1] + 2)
|
||||||
legal_moves.append(self.get_possible_move_down(from_, color))
|
move_up_left_two = (from_[0] - 2, from_[1] - 2)
|
||||||
return legal_moves
|
move_up_right_two = (from_[0] - 2, from_[1] + 2)
|
||||||
|
if self.check_move_legal(from_, move_down_left_two, color) != False:
|
||||||
|
legal_moves.append((from_, move_down_left_two))
|
||||||
|
if self.check_move_legal(from_, move_down_right_two, color) != False:
|
||||||
|
legal_moves.append((from_, move_down_right_two))
|
||||||
|
if self.check_move_legal(from_, move_up_left_two, color) != False:
|
||||||
|
legal_moves.append((from_, move_up_left_two))
|
||||||
|
if self.check_move_legal(from_, move_up_right_two, color) != False:
|
||||||
|
legal_moves.append((from_, move_up_right_two))
|
||||||
|
return legal_moves
|
||||||
|
|
||||||
|
def get_possible_move_non_capture(self, from_, color):
|
||||||
|
# all non-capturing moves
|
||||||
|
legal_moves = []
|
||||||
|
move_down_left_one = (from_[0] + 1, from_[1] - 1)
|
||||||
|
move_down_right_one = (from_[0] + 1, from_[1] + 1)
|
||||||
|
move_up_left_one = (from_[0] - 1, from_[1] - 1)
|
||||||
|
move_up_right_one = (from_[0] - 1, from_[1] + 1)
|
||||||
|
if self.check_move_legal(from_, move_down_left_one, color) != False:
|
||||||
|
legal_moves.append((from_, move_down_left_one))
|
||||||
|
if self.check_move_legal(from_, move_down_right_one, color) != False:
|
||||||
|
legal_moves.append((from_, move_down_right_one))
|
||||||
|
if self.check_move_legal(from_, move_up_left_one, color) != False:
|
||||||
|
legal_moves.append((from_, move_up_left_one))
|
||||||
|
if self.check_move_legal(from_, move_up_right_one, color) != False:
|
||||||
|
legal_moves.append((from_, move_up_right_one))
|
||||||
|
return legal_moves
|
||||||
|
|
||||||
def get_possible_moves(self, color):
|
def get_possible_moves(self, color):
|
||||||
# toDo: get possible moves for single piece, then iterate through all pieces
|
# toDo: get possible moves for single piece, then iterate through all pieces
|
||||||
legal_moves = []
|
legal_moves = []
|
||||||
if color == "white":
|
captures = []
|
||||||
for white_position in self.white_positions:
|
if color == "white":
|
||||||
print((white_position[0], white_position[1]))
|
for white_position in self.white_positions:
|
||||||
legal_moves.append(self.get_possible_move((white_position[0], white_position[1]), color))
|
# print((white_position[0], white_position[1]))
|
||||||
elif color == "black":
|
legal_moves += self.get_possible_move_non_capture(
|
||||||
for black_position in self.black_positions:
|
(white_position[0], white_position[1]), color)
|
||||||
legal_moves.append(self.get_possible_move((black_position[0], black_position[1]), color))
|
captures += self.get_possible_move_capture(
|
||||||
return legal_moves
|
(white_position[0], white_position[1]), color)
|
||||||
|
elif color == "black":
|
||||||
def alpha_beta(self, depth, alpha, beta, player):
|
for black_position in self.black_positions:
|
||||||
if depth == 0:
|
legal_moves += self.get_possible_move_non_capture(
|
||||||
return self.evaluate(), None
|
(black_position[0], black_position[1]), color)
|
||||||
|
captures += self.get_possible_move_capture(
|
||||||
if player == 'x':
|
(black_position[0], black_position[1]), color)
|
||||||
max_eval = float('-inf')
|
print('CAPTURES: ')
|
||||||
best_move = None
|
print(captures)
|
||||||
|
# if len(captures) > 0:
|
||||||
for move in self.get_possible_moves(player):
|
# print('CAPTURE POSSIBLE')
|
||||||
new_state = copy.deepcopy(self)
|
# print(captures)
|
||||||
new_state.move(*move)
|
# return captures
|
||||||
eval, _ = alpha_beta(new_state, depth-1, alpha, beta, 'o')
|
print('LEGAL MOVES')
|
||||||
|
print(legal_moves + captures)
|
||||||
if eval > max_eval:
|
return legal_moves + captures
|
||||||
max_eval = eval
|
|
||||||
best_move = move
|
def alpha_beta(self, depth, alpha, beta, color):
|
||||||
|
if depth == 0:
|
||||||
alpha = max(alpha, eval)
|
return self.evaluate(), None
|
||||||
|
|
||||||
if alpha >= beta:
|
if color == 'white':
|
||||||
break
|
max_eval = float('-inf')
|
||||||
|
best_move = None
|
||||||
return max_eval, best_move
|
|
||||||
|
for move in self.get_possible_moves(color):
|
||||||
else:
|
new_state = copy.deepcopy(self)
|
||||||
min_eval = float('inf')
|
new_state.make_move(*move, 'white')
|
||||||
best_move = None
|
eval, _ = new_state.alpha_beta(depth-1, alpha, beta, 'black')
|
||||||
|
|
||||||
for move in state.get_possible_moves(player):
|
if eval > max_eval:
|
||||||
new_state = copy.deepcopy(state)
|
max_eval = eval
|
||||||
new_state.move(*move)
|
best_move = move
|
||||||
eval, _ = alpha_beta(new_state, depth-1, alpha, beta, 'x')
|
|
||||||
|
alpha = max(alpha, eval)
|
||||||
if eval < min_eval:
|
|
||||||
min_eval = eval
|
if alpha >= beta:
|
||||||
best_move = move
|
break
|
||||||
|
|
||||||
beta = min(beta, eval)
|
return max_eval, best_move
|
||||||
|
|
||||||
if beta <= alpha:
|
else:
|
||||||
break
|
min_eval = float('inf')
|
||||||
|
best_move = None
|
||||||
return min_eval, best_move
|
|
||||||
|
for move in self.get_possible_moves(color):
|
||||||
|
new_state = copy.deepcopy(self)
|
||||||
|
new_state.make_move(*move, 'black')
|
||||||
|
eval, _ = new_state.alpha_beta(depth-1, alpha, beta, 'white')
|
||||||
|
|
||||||
|
if eval < min_eval:
|
||||||
|
min_eval = eval
|
||||||
|
best_move = move
|
||||||
|
|
||||||
|
beta = min(beta, eval)
|
||||||
|
|
||||||
|
if beta <= alpha:
|
||||||
|
break
|
||||||
|
|
||||||
|
return min_eval, best_move
|
||||||
|
|
||||||
def evaluate(self):
|
def evaluate(self):
|
||||||
white_score = 0
|
white_score = 0
|
||||||
black_score = 0
|
black_score = 0
|
||||||
|
|
||||||
for white_position in self.white_positions:
|
for white_position in self.white_positions:
|
||||||
if white_position[2]:
|
if white_position[2]:
|
||||||
white_score += 2
|
white_score += 10
|
||||||
else:
|
else:
|
||||||
white_score += 2
|
white_score += 5
|
||||||
|
|
||||||
for black_position in self.black_positions:
|
for black_position in self.black_positions:
|
||||||
if black_position[2]:
|
if black_position[2]:
|
||||||
black_score += 2
|
black_score += 10
|
||||||
else:
|
else:
|
||||||
black_score += 2
|
black_score += 5
|
||||||
|
|
||||||
return x_score - o_score
|
return white_score - black_score
|
||||||
|
|
||||||
def input_to_coordinates(self, input):
|
def input_to_coordinates(self, input):
|
||||||
pos_x = ord(input[0])-ord('a')
|
pos_x = ord(input[0])-ord('a')
|
||||||
pos_y = int(input[1::])
|
pos_y = int(input[1::])
|
||||||
return pos_x, pos_y
|
return pos_x, pos_y
|
||||||
|
|
||||||
def handle_player_move(self, color):
|
def handle_player_move(self, color):
|
||||||
has_moved = False
|
has_moved = False
|
||||||
while not has_moved:
|
while not has_moved:
|
||||||
user_input = input('How do you want to move? (format: d6 e5)\n')
|
user_input = input('How do you want to move? (format: d6 e5)\n')
|
||||||
regex = r"^[A-Za-z]\d+\s[A-Za-z]\d+$"
|
regex = r"^[a-z]\d+\s[a-z]\d+$"
|
||||||
match = re.search(regex, user_input)
|
match = re.search(regex, user_input)
|
||||||
if not match:
|
if not match:
|
||||||
print('Invalid input, try again')
|
print('Invalid input, try again')
|
||||||
@ -312,9 +342,17 @@ class Game:
|
|||||||
self.print_board()
|
self.print_board()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# Ran first in the code
|
# Ran first in the code
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
game = Game(8)
|
game = Game(8)
|
||||||
game.print_board()
|
while True:
|
||||||
game.handle_player_move('black')
|
game.print_board()
|
||||||
|
possible_moves_black = game.get_possible_moves('black')
|
||||||
|
if len(possible_moves_black) == 0:
|
||||||
|
print('Game over. White wins')
|
||||||
|
game.handle_player_move('black')
|
||||||
|
possible_moves_white = game.get_possible_moves('black')
|
||||||
|
if len(possible_moves_white) == 0:
|
||||||
|
print('Game over. Black wins')
|
||||||
|
_, ai_move = game.alpha_beta(1, 5, 10, 'white')
|
||||||
|
game.make_move(ai_move[0], ai_move[1], 'white')
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user