Skip to content
This repository has been archived by the owner on Apr 24, 2019. It is now read-only.

Commit

Permalink
Experiment with AI hash
Browse files Browse the repository at this point in the history
  • Loading branch information
medwards1771 committed Apr 24, 2018
1 parent f21ac81 commit 4198669
Showing 1 changed file with 15 additions and 24 deletions.
39 changes: 15 additions & 24 deletions tic-tac-toe/lib/board.rb
Expand Up @@ -3,10 +3,13 @@ class Board


NO_MOVE = -1 NO_MOVE = -1
POSITIONS_ON_BOARD = (0..8) POSITIONS_ON_BOARD = (0..8)
ROW_STEP = 1
RIGHT_DIAGONAL_STEP = 2 GAME_AI = {
COLUMN_STEP = 3 row: { step: 1, first_positions: [0, 3, 6] },
LEFT_DIAGONAL_STEP = 4 column: { step: 3, first_positions: [0, 1, 2] },
left_diagonal: { step: 4, first_positions: [0] },
right_diagonal: { step: 2, first_positions: [2] },
}


def initialize(state = "---------") def initialize(state = "---------")
@state = state @state = state
Expand All @@ -28,29 +31,17 @@ def winning_move?(player)
end end


def winner def winner
first_position_in_rows = [0, 3, 6] GAME_AI.each do |direction, attrs|
first_position_in_rows.each { |position| return mark_at(position) if winning_combo?(position, "ROW") } attrs[:first_positions].any? do |position|

return mark_at(position) if winning_combo?(position, attrs[:step])
first_position_in_columns = [0, 1, 2] end
first_position_in_columns.each { |position| return mark_at(position) if winning_combo?(position, "COLUMN") } end

first_position_in_left_diagonal = 0
return mark_at(first_position_in_left_diagonal) if winning_combo?(first_position_in_left_diagonal, "LEFT_DIAGONAL")

first_position_in_right_diagonal = 2
return mark_at(first_position_in_right_diagonal) if winning_combo?(first_position_in_right_diagonal, "RIGHT_DIAGONAL")

return '-'
end end


def winning_combo?(position, direction) def winning_combo?(position, step)
position_occupied?(position) && position_occupied?(position) &&
mark_at(position) == mark_at(position + step_for(direction)) && mark_at(position) == mark_at(position + step) &&
mark_at(position + step_for(direction)) == mark_at(position + step_for(direction) * 2) mark_at(position + step) == mark_at(position + step * 2)
end

def step_for(direction)
self.class.const_get("#{direction}_STEP")
end end


def position_unoccupied?(position) def position_unoccupied?(position)
Expand Down

1 comment on commit 4198669

@edgenard
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is fancy? How did you come up with this?

Please sign in to comment.