class TicTacToeRZ::GamePlay::ComputerActions

Attributes

current_player[R]
game_board[R]
other_player[R]

Public Class Methods

new(game_board, player_manager) click to toggle source
# File lib/tic_tac_toe_rz/tictactoeruby.core/gameplay/computer_actions.rb, line 16
def initialize(game_board, player_manager)
  raise Exceptions::NilReferenceError, "game_board" if game_board.nil?
  raise Exceptions::NilReferenceError, "player_manager" if player_manager.nil?
  @game_board = game_board
  @current_player = player_manager.current_player.symbol
  @other_player = player_manager.get_next_player.symbol
end

Public Instance Methods

get_best_move(board, player_symbol, depth, best_max_value, best_min_value) click to toggle source
# File lib/tic_tac_toe_rz/tictactoeruby.core/gameplay/computer_actions.rb, line 28
def get_best_move(board, player_symbol, depth, best_max_value, best_min_value)
  raise Exceptions::NilReferenceError, "board" if board.nil?
  raise Exceptions::InvalidValueError, "player_symbol" if !Validators::PlayerSymbolValidator.valid?(player_symbol)
  next_moves = GameRules::AvailableSpacesRules.get_available_spaces(board)
  tile = ""
  current_score = 0
  best_move = -1

  current = player_symbol == current_player
  if current 
      opposing_symbol = other_player
  else
      opposing_symbol = current_player
  end

  win_exists = GameRules::GameOverRules.win_for_player?(player_symbol, board) || GameRules::GameOverRules.win_for_player?(opposing_symbol, board)
  
  if next_moves.size == 0 || depth == 0 || win_exists
    current_score = Evaluators::BoardScoreEvaluator.score_of_board(board, current_player, other_player) * (depth + 1)
    move = GamePlay::WeightedMove.new(best_move, current_score)
    return move
  end

  next_moves.each do |move|
    tile = board[move]
    board[move] = player_symbol
      current_score = get_best_move(board, opposing_symbol, depth - 1, best_max_value, best_min_value).score
    if current
      if current_score > best_max_value
        best_max_value = current_score
        best_move = move
            end
    else
      if current_score < best_min_value
        best_min_value = current_score
        best_move = move
      end
          end

    reset_board_tile(board, move, tile)
    found_best_route = best_max_value >= best_min_value

    break if found_best_route
  end
  if current
    score = best_max_value
  else
    score = best_min_value
  end

  weighted_move = GamePlay::WeightedMove.new(best_move, score)
  return weighted_move
end
reset_board_tile(board, move, tile) click to toggle source
# File lib/tic_tac_toe_rz/tictactoeruby.core/gameplay/computer_actions.rb, line 24
def reset_board_tile(board, move, tile)
  board[move] = tile
end