I recently built an unbeatable game of tic tac toe. It was a fun and very humbling project that taught me a ton. If you want to get totally schooled, give the tic tac toe game a shot here . In order to make the game unbeatable, it was necessary to create an algorithm that could calculate all the possible moves available for the computer player and use some metric to determine the best possible move. After extensive research it became clear that the Minimax algorithm was right for the job.
Fighting the Good Fight: Depth
We will subtract the depth, that is the number of turns, or recursions, from the end game score, the more turns the lower the score, the fewer turns the higher the score.
https://chessprogramming.wikispaces.com/Minimax
https://www.cs.tcd.ie/Glenn.Strong/3d5/minimax-notes.pdf
http://beej.us/blog/data/minimax/
Read full article from Tic Tac Toe: Understanding the Minimax Algorithm - Never Stop Building
Fighting the Good Fight: Depth
We will subtract the depth, that is the number of turns, or recursions, from the end game score, the more turns the lower the score, the fewer turns the higher the score.
def score(game, depth)
if game.win?(@player)
return 10 - depth
elsif game.win?(@opponent)
return depth - 10
else
return 0
end
end
def minimax(game, depth)
return score(game) if game.over?
depth += 1
scores = [] # an array of scores
moves = [] # an array of moves
# Populate the scores array, recursing as needed
game.get_available_moves.each do |move|
possible_game = game.get_new_state(move)
scores.push minimax(possible_game, depth)
moves.push move
end
# Do the min or the max calculation
if game.active_turn == @player
# This is the max calculation
max_score_index = scores.each_with_index.max[1]
@choice = moves[max_score_index]
return scores[max_score_index]
else
# This is the min calculation
min_score_index = scores.each_with_index.min[1]
@choice = moves[min_score_index]
return scores[min_score_index]
end
end
Frequently, in game theory, maximin is distinct from minimax. Minimax is used in zero-sum games to denote minimizing the opponent's maximum payoff. In a zero-sum game, this is identical to minimizing one's own maximum loss, and to maximizing one's own minimum gain.
"Maximin" is a term commonly used for non-zero-sum games to describe the strategy which maximizes one's own minimum payoff. In non-zero-sum games, this is not generally the same as minimizing the opponent's maximum gain, nor the same as the Nash equilibrium strategy.
Also checkhttps://chessprogramming.wikispaces.com/Minimax
https://www.cs.tcd.ie/Glenn.Strong/3d5/minimax-notes.pdf
http://beej.us/blog/data/minimax/
Read full article from Tic Tac Toe: Understanding the Minimax Algorithm - Never Stop Building