Skip to content

Instantly share code, notes, and snippets.

@dlynam
Created October 16, 2015 05:57
Show Gist options
  • Select an option

  • Save dlynam/99e8909a856a376ff2df to your computer and use it in GitHub Desktop.

Select an option

Save dlynam/99e8909a856a376ff2df to your computer and use it in GitHub Desktop.
class TicTacToe
attr_accessor :board, :winner
attr_reader :winning_positions
def initialize
@board = create_board
@winner = nil
@winning_positions = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7] ]
end
def play
while !game_over?
player_turn
comp_turn
draw_board
end
output_winner
end
def game_over?
winner? || tie?
end
def output_winner
if winner
puts "#{winner} won!"
else
puts "It's a tie."
end
end
def draw_board
puts " #{board[1]} | #{board[2]} | #{board[3]} "
puts "------------------"
puts " #{board[4]} | #{board[5]} | #{board[6]} "
puts "------------------"
puts " #{board[7]} | #{board[8]} | #{board[9]} "
end
def winner?
winning_positions.each do |position|
if board[position[0]] == 'x' and board[position[1]] == 'x' and board[position[2]] == 'x'
self.winner = 'Player'
return true
elsif board[position[0]] == 'o' and board[position[1]] == 'o' and board[position[2]] == 'o'
self.winner = 'Computer'
return true
end
end
false
end
def player_turn
puts "Choose square (1--9)"
choice = gets.chomp.to_i
unless board.select {|k, v| v == ' '}.keys.include?(choice)
puts "You must pick an empty square."
choice = gets.chomp.to_i
end
self.board[choice] = 'x'
end
def comp_turn
choice = board.select {|k,v| v == ' '}.keys.sample
self.board[choice] = 'o'
end
def tie?
board.select {|k,v| v == ' '}.keys.empty?
end
private
def create_board
hash = {}
(1..9).each {|n| hash[n] = ' '}
hash
end
end
TicTacToe.new.play
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment