Sha256: 98ed7c2d0b5aa59fea31174e7a6f3b7270f01a6994150c5a9c0ccb97ec852569

Contents?: true

Size: 1.8 KB

Versions: 2

Compression:

Stored size: 1.8 KB

Contents

require 'tictactoe_tracypholmes/board'
require 'tictactoe_tracypholmes/player'


module TictactoeTracypholmes
  module Players
    class Players::Computer < Player # represents a computer player of Tic Tac Toe. Implement a #move method that accepts a board and returns the move the computer wants to make in the form of a 1-9 string.


      def move(board)
        move = nil

        # Center move if possible
        if !board.taken?(5)
          move = '5'
        # If player2 and the scoundrel took 5, goto the first position
        elsif board.turn_count == 1
          move = '1'
        # Go for the corners! Presumes you went first
        elsif board.turn_count == 2
          move = [1, 3, 7, 9].find{|i| !board.taken?(i)}.to_s

        # Player2 side strategy
        elsif board.turn_count == 3 && (board.position(1) == board.position(9) || board.position(3) == board.position(7))
          move = "2"

        # You worked hard on these combinations - let's see who has the best combos thus far
        else Game::WIN_COMBINATIONS.find do |c|

          # Do I have a winner?
          if c.select{|i| board.position(i+1) == token}.size == 2 && c.any?{|i| board.position(i+1) == " "}
            move = c.select{|i| !board.taken?(i+1)}.first.to_i.+(1).to_s

          # No winner - let's block the other guy
          elsif c.select{|i| board.position(i+1) != " " && board.position(i+1) != token}.size == 2 && c.any?{|i| board.position(i+1) == " "}
            move = c.select{|i| !board.taken?(i+1)}.first.to_i.+(1).to_s
          end
        end

        # No one has a winner, let's play out the corners and sides if possible
        move = [1, 3, 7, 9, 2, 4, 6, 8].find{|i| !board.taken?(i)}.to_s if move == nil
        end
        move

      #  input = (1..9).to_a.sample
      #  input.to_s
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
tictactoe_tracypholmes-0.1.3 lib/tictactoe_tracypholmes/players/computer.rb
tictactoe_tracypholmes-0.1.0 lib/tictactoe_tracypholmes/players/computer.rb