Hello, I am new to Rust and so I've been practicing by creating a simple tic-tac-toe game. I implemented a simple alpha-beta pruning algorithm for the opponent's ai implemented as follows:
fn alpha_beta(
&self,
player: &Player,
depth: u32,
alpha: &MoveScoreTurns,
beta: &MoveScoreTurns,
) -> MoveScoreTurns {
// Base case
if depth == 0 || self.game_status != GameStatus::StillPlaying {
return MoveScoreTurns {
score: self.game_status,
turns_to_win: depth,
player_move: Point { x: 0, y: 0 },
};
}
match player {
Player::X => {
let mut value = MoveScoreTurns::MIN;
let mut new_alpha = alpha.clone();
let mut new_value;
for blank_square in &self.blank_squares_set {
let mut new_board = self.clone();
new_board.insert(blank_square, player.square_type());
new_value = new_board.alpha_beta(&player.other(), depth - 1, &new_alpha, beta);
new_value.player_move = *blank_square;
value = std::cmp::max(value.clone(), new_value.clone());
if new_value > *beta {
break;
}
// _new_alpha = std::cmp::max(alpha.clone(), value.clone());
new_alpha = std::cmp::max(value.clone(), new_alpha.clone());
}
value.clone()
}
Player::O => {
let mut value = MoveScoreTurns::MAX;
let mut new_beta = beta.clone();
let mut new_value;
for blank_square in &self.blank_squares_set {
let mut new_board = self.clone();
new_board.insert(blank_square, player.square_type());
new_value = new_board.alpha_beta(&player.other(), depth - 1, alpha, &new_beta);
new_value.player_move = *blank_square;
value = std::cmp::min(value.clone(), new_value.clone());
if new_value < *alpha {
break;
}
new_beta = std::cmp::min(value.clone(), new_beta.clone());
}
value.clone()
}
}
}
While this works I feel that there should be a better way of doing this. I have two main questions.
- Is there a way to reduce the number of calls to
.clone()
? - There is a lot of code duplication between the two
match
branches. Is there a way to reduce this?
I apologize in advance if this is a topic better suited for help rather than code review, but I figured since I am asking for assistance when it comes to refactoring rather than writing, this would be the place to go.