Class: TicTacToe::MinimaxPlayer

Inherits:
Player
  • Object
show all
Defined in:
lib/game_tictactoe_alu4078/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



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/game_tictactoe_alu4078/minimaxplayer.rb', line 5

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



62
63
64
65
66
67
68
# File 'lib/game_tictactoe_alu4078/minimaxplayer.rb', line 62

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

#search_best_move(board, mark, level) ⇒ Object



25
26
27
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
# File 'lib/game_tictactoe_alu4078/minimaxplayer.rb', line 25

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