Skip to content

Commit

Permalink
get minimax working minus recursions
Browse files Browse the repository at this point in the history
  • Loading branch information
IanDCarroll committed Jul 3, 2017
1 parent cfc6703 commit 4a92363
Show file tree
Hide file tree
Showing 5 changed files with 424 additions and 10 deletions.
2 changes: 1 addition & 1 deletion lib/ai/computer_player.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
class ComputerPlayer

def initialize(board)
@board = board.dup
@board = board
@ai = Minimax.new(@board)
end

Expand Down
64 changes: 63 additions & 1 deletion lib/ai/minimax.rb
Original file line number Diff line number Diff line change
@@ -1,12 +1,74 @@
require "game_constants"
require "reporter"

class Minimax
attr_reader :spaces
attr_accessor :recursion_depth

def initialize(board)
@board = board
@const = GameConstants.new
@judge = Reporter.new
@board = board.dup
@spaces = @board.spaces
@recursion_depth = 0
end

def choose #first available to validate integration
@board.available_spaces[0]
end

def available_spaces
@board.available_spaces
end

# recursion dependent ==v

def score_spaces(spaces = @spaces)
@recursion_depth += 1
scored_spaces = spaces
available_spaces.each do |space|
scored_spaces[space] = score_space(space)
end
@recursion_depth -= 1
scored_spaces
end

def score_space(space)
scenario = report(space)
if scenario == @const.winner(@const.players[1]) then return 1
elsif scenario == @const.winner(@const.players[0]) then return -1
elsif scenario == @const.draw then return 0
else 2 end
end

def report(space)
@judge.report({ space: space,
board: trial_spaces(space) })
end

def trial_spaces(space)
trial_spaces = @spaces.dup
trial_spaces[space] = appropriate_player
trial_spaces
end

def appropriate_player
@recursion_depth.odd? ? @const.players[1] : @const.players[0]
end

# recursion_dependent ==^

def make_ultimate_choice(scored_spaces)
ultimate_choice = "no ultimate choice made"
best_score_so_far = -1
scored_spaces.each do |space|
unless space.instance_of?(String)
if space >= best_score_so_far
best_score_so_far = space
ultimate_choice = scored_spaces.index(space)
end
end
end
ultimate_choice
end
end
7 changes: 5 additions & 2 deletions lib/reporter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,15 @@ def win?(board)
def winning_set?(board, winning_set)
win = []
winning_set.each { |space| win << board[space] }
unless win.uniq == [nil] then win.uniq.length == 1 end
unless win.uniq[0].nil? || win.uniq[0].instance_of?(Integer)
win.uniq.length == 1
end
end

def empty_spaces?(board)
(0...board.length).each { |i|
if board[i] == nil
if board[i].nil? || board[i].instance_of?(Integer)

return true
end }
false
Expand Down
Loading

0 comments on commit 4a92363

Please sign in to comment.