Class: Tictactoe::MinimaxPlayer

Inherits:
Player
  • Object
show all
Defined in:
lib/tictactoe/minimaxplayer.rb

Instance Attribute Summary

Attributes inherited from Player

#mark

Instance Method Summary collapse

Methods inherited from Player

#finish, #initialize

Constructor Details

This class inherits a constructor from Tictactoe::Player

Instance Method Details

#move(board) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/tictactoe/minimaxplayer.rb', line 8

def move( board )
    # Obtains the available movements
      moves = board.moves

      # For each available movement
      bestValue = -2
      bestMove = ""
      moves.each do |mov|
        newsquares = board.squares.dup
        newboard = Board.new(newsquares)
        newboard[mov] = self.mark
        value = search_best_move(newboard, opponent_mark, 1)
        if (value > bestValue)
bestValue = value
bestMove = mov
        end
      end
      bestMove
end

#opponent_markObject



65
66
67
68
69
70
71
# File 'lib/tictactoe/minimaxplayer.rb', line 65

def opponent_mark
  if (self.mark == "X")
    return "O"
  else
    return "X"
  end
end

#search_best_move(board, mark, level) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/tictactoe/minimaxplayer.rb', line 28

def search_best_move(board, mark, level)
  # Checks if there is a winner  
  return 1 if (board.won? == self.mark)
  return 0 if (board.won? == " ")
  return -1 if (board.won? == opponent_mark)
     
  # Gets the available movements
  moves = board.moves

  # Min level
  if ((level % 2 == 1) && (!board.won?))
    bestValue = 2
    moves.each do |mov|
      newsquares = board.squares.dup
      newboard = Board.new(newsquares)
      newboard[mov] = mark
      value = search_best_move(newboard, self.mark, level + 1)
      if (value < bestValue)
        bestValue = value
      end
    end
  # Max level
  elsif ((level % 2 == 0) && (!board.won?))
    bestValue = -2
    moves.each do |mov|
      newsquares = board.squares.dup
      newboard = Board.new(newsquares)
      newboard[mov] = mark
      value = search_best_move(newboard, opponent_mark, level + 1)
      if (value > bestValue)
        bestValue = value
      end
        end
  end
  bestValue
end