Class: TTT::Rating

Inherits:
Object
  • Object
show all
Defined in:
lib/ttt/ratings.rb

Overview

Not used actively in the program Instead, it is used to precalculate the ratings below

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(game_or_board = '000000000', parent = nil) ⇒ Rating

Returns a new instance of Rating.



9
10
11
12
13
# File 'lib/ttt/ratings.rb', line 9

def initialize(game_or_board='000000000', parent=nil)
  game_or_board = Game.new game_or_board unless game_or_board.is_a? Game
  self.game = game_or_board
  self.parent = parent
end

Instance Attribute Details

#childrenObject

Returns the value of attribute children.



7
8
9
# File 'lib/ttt/ratings.rb', line 7

def children
  @children
end

#gameObject

Returns the value of attribute game.



7
8
9
# File 'lib/ttt/ratings.rb', line 7

def game
  @game
end

#parentObject

Returns the value of attribute parent.



7
8
9
# File 'lib/ttt/ratings.rb', line 7

def parent
  @parent
end

Instance Method Details

#leaf?Boolean

Returns:

  • (Boolean)


29
30
31
# File 'lib/ttt/ratings.rb', line 29

def leaf?
  children.empty?
end

#rating_for(player_number) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/ttt/ratings.rb', line 33

def rating_for(player_number)
  if leaf?
    return 0  if game.tie?
    return 1  if game.winner == player_number
    return -1
  else
    ratings = children.map { |_, child| child.rating_for player_number }
    crnt_player = game.turn
    if crnt_player == player_number
      return  1 if ratings.any? { |rating| rating ==  1 }   # if my turn, and I can move to a win, then I win
      return -1 if ratings.all? { |rating| rating == -1 }   # if my turn, and all moves are losses, then I lose
      ratings.reject! { |rating| rating == -1 }
      return ratings.inject(:+).to_f / ratings.size         # otherwise, rating is the average of non-losing moves (I will never make a losing move)
    else
      return -1 if ratings.any? { |rating| rating == -1 }   # if his turn, and he can win, then I lose
      return  1 if ratings.all? { |rating| rating ==  1 }   # if his turn, and all his moves lead to wins for me, then I win
      return ratings.inject(:+).to_f / ratings.size         # otherwise, rating is the average of possible move scores
    end
  end
end

#to_sObject



15
16
17
# File 'lib/ttt/ratings.rb', line 15

def to_s
  game.board :ttt
end