Created
December 2, 2014 23:12
-
-
Save falonofthetower/9a4c399514ab25f97461 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'pry' | |
WINS = [[1,2,3], [4,5,6], [7,8,9], | |
[1,4,7], [2,5,8], [3,6,9], | |
[1,5,9], [3,5,7]] | |
def initialize_board | |
board = Hash[(1..9).to_a.zip((1..9).to_a)] | |
end | |
def post_board(positions) | |
system ("clear") | |
puts " | | " | |
puts " #{positions[1]} | #{positions[2]} | #{positions[3]} " | |
puts " | | " | |
puts "-----+-----+-----" | |
puts " | | " | |
puts " #{positions[4]} | #{positions[5]} | #{positions[6]} " | |
puts " | | " | |
puts "-----+-----+-----" | |
puts " | | " | |
puts " #{positions[7]} | #{positions[8]} | #{positions[9]} " | |
puts " | | " | |
end | |
def spaces_available(positions) | |
positions.select {|k,v| (1..9).include?(v) } | |
end | |
def get_player_choice(positions,msg='') | |
puts "Pick your poison 1-9" | |
input = gets.chomp.to_i | |
if spaces_available(positions).include?(input) | |
positions[input] = "X" | |
else | |
get_player_choice(positions,"Not available: Try Again") | |
end | |
end | |
def create_computer_choice(positions) | |
positions[spaces_available(positions).keys.sample] = "O" | |
end | |
def winner?(positions) | |
if positions.select { |_,v| v == "X" }.keys.permutation(3).to_a & WINS != [] | |
elsif positions.select { |_,v| v == "O" }.keys.permutation(3).to_a & WINS != [] | |
end | |
end | |
def all_squares_taken?(positions) | |
spaces_available(positions) == {} | |
end | |
positions = initialize_board | |
begin | |
post_board(positions) | |
get_player_choice(positions) | |
create_computer_choice(positions) | |
post_board(positions) | |
winner = winner?(positions) | |
end until winner || all_squares_taken?(positions) | |
if winner | |
puts "Its a winner" | |
else | |
puts "It's a tie" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment