jdl_tictactoe 0.0.4 → 0.0.5
Sign up to get free protection for your applications and to get access to all the features.
- data/lib/jdl_tictactoe/board.rb +1 -1
- data/lib/jdl_tictactoe/player.rb +43 -41
- data/lib/jdl_tictactoe.rb +0 -9
- metadata +1 -1
data/lib/jdl_tictactoe/board.rb
CHANGED
data/lib/jdl_tictactoe/player.rb
CHANGED
@@ -1,57 +1,59 @@
|
|
1
|
-
|
1
|
+
module JdlTicTacToe
|
2
|
+
class Player
|
2
3
|
|
3
|
-
|
4
|
+
attr_accessor :species, :mark, :opponent
|
4
5
|
|
5
|
-
|
6
|
-
|
7
|
-
|
8
|
-
|
9
|
-
|
6
|
+
def initialize(species, mark="X")
|
7
|
+
@species = "human" if species == "H"
|
8
|
+
@species = "computer" if species == "C"
|
9
|
+
@mark = mark
|
10
|
+
end
|
10
11
|
|
11
|
-
|
12
|
-
|
13
|
-
|
12
|
+
def mark_square(board, square)
|
13
|
+
board.mark_square(square, @mark)
|
14
|
+
end
|
14
15
|
|
15
|
-
|
16
|
-
|
17
|
-
|
18
|
-
|
19
|
-
|
20
|
-
|
21
|
-
|
22
|
-
|
16
|
+
def minimax(game, turn)
|
17
|
+
if game.empty_squares.count == 9
|
18
|
+
return 1
|
19
|
+
elsif game.empty_squares.count == 8
|
20
|
+
return 5 if game.empty_squares.include?(5)
|
21
|
+
return 1 if !game.empty_squares.include?(5)
|
22
|
+
else
|
23
|
+
return get_minimax_square(game, turn)
|
24
|
+
end
|
23
25
|
end
|
24
|
-
end
|
25
26
|
|
26
|
-
|
27
|
-
|
28
|
-
|
27
|
+
def get_minimax_scores(game, turn)
|
28
|
+
scores = []
|
29
|
+
return [game.board.score(self)] if game.over?
|
29
30
|
|
30
|
-
|
31
|
-
|
32
|
-
|
31
|
+
game.empty_squares.each do |move|
|
32
|
+
game.mark_square(move, game.send(turn).mark)
|
33
|
+
minimax_scores = get_minimax_scores(game, game.switch_turn(turn))
|
33
34
|
|
34
|
-
|
35
|
-
|
36
|
-
|
37
|
-
|
38
|
-
|
35
|
+
if game.send(turn) == self
|
36
|
+
scores << minimax_scores.min
|
37
|
+
elsif game.send(turn) != self
|
38
|
+
scores << minimax_scores.max
|
39
|
+
end
|
39
40
|
|
40
|
-
|
41
|
+
game.undo_move(move)
|
42
|
+
end
|
43
|
+
return scores
|
41
44
|
end
|
42
|
-
return scores
|
43
|
-
end
|
44
45
|
|
45
|
-
|
46
|
-
|
47
|
-
|
46
|
+
def get_minimax_square(game, turn)
|
47
|
+
moves_with_score = {}
|
48
|
+
scores = get_minimax_scores(game, turn)
|
48
49
|
|
49
|
-
|
50
|
-
|
50
|
+
game.empty_squares.each_with_index do |move, index|
|
51
|
+
moves_with_score[move] = scores[index]
|
52
|
+
end
|
53
|
+
|
54
|
+
max = moves_with_score.values.max
|
55
|
+
return moves_with_score.select { |k,v| v == max }.keys.first
|
51
56
|
end
|
52
57
|
|
53
|
-
max = moves_with_score.values.max
|
54
|
-
return moves_with_score.select { |k,v| v == max }.keys.first
|
55
58
|
end
|
56
|
-
|
57
59
|
end
|
data/lib/jdl_tictactoe.rb
CHANGED