Class: Tictactoe::MinimaxPlayer
- Inherits:
-
Player
- Object
- Player
- Tictactoe::MinimaxPlayer
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
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 )
moves = board.moves
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_mark ⇒ Object
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)
return 1 if (board.won? == self.mark)
return 0 if (board.won? == " ")
return -1 if (board.won? == opponent_mark)
moves = board.moves
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
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
|