Skip to content

Instantly share code, notes, and snippets.

@neurodynamic
Created July 12, 2016 00:32
Show Gist options
  • Save neurodynamic/2452f9dd03c3f368821fe8bf1d16ffad to your computer and use it in GitHub Desktop.
Save neurodynamic/2452f9dd03c3f368821fe8bf1d16ffad to your computer and use it in GitHub Desktop.
Simple Ruby Tic Tac Toe
class Board
def initialize
@rows = three_blank_rows
end
def playable_cell?(row, col)
return false unless (1..3).cover?(row) && (1..3).cover?(col)
@rows[col - 1][row - 1] == ' '
end
def play(row, col, string)
@rows[col - 1][row - 1] = string
end
def to_s
row_strings = @rows.map { |row| row.join(' | ') }
row_strings.join("\n---------\n")
end
def winner
players.find { |player| wins?(player) }
end
private
def players
@rows.flatten.uniq.delete_if { |cell| cell == ' ' }
end
def wins?(player)
winnable_paths.any? { |path| completed_by?(player, path) }
end
def completed_by?(player, path)
path.all? { |cell| cell == player }
end
def winnable_paths
paths = @rows # horizontal paths
paths += @rows.transpose # vertical paths
paths << [@rows[0][0], @rows[1][1], @rows[2][2]] # ascending diagonal path
paths << [@rows[0][2], @rows[1][1], @rows[2][0]] # descending diagonal path
paths
end
def three_blank_rows
Array.new(3) { blank_row }
end
def blank_row
Array.new(3, ' ')
end
end
require_relative 'board'
def get_play_choices
puts "Enter the row you'd like to play in (from 1 to 3)."
row = gets.chomp.to_i
puts "Enter the column you'd like to play in (from 1 to 3)."
column = gets.chomp.to_i
[row, column]
end
board = Board.new
turn = 1
until board.winner
player = turn.odd? ? 'X' : 'O'
puts "Play your turn, player #{player}.\n"
row, column = get_play_choices
until board.playable_cell?(row, column)
puts "You can't play there.\n"
row, column = get_play_choices
end
board.play(row, column, player)
puts "#{board}\n"
turn += 1
end
puts "#{board.winner} wins!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment