Created
August 8, 2020 01:11
-
-
Save datt/47369e6c7771c3a89f9218fa4495f173 to your computer and use it in GitHub Desktop.
Tic Tac Toe solution in Ruby
This file contains 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
class TicTacToeBoard | |
SYMBOLS = ['X', 'Y'] | |
WINNING = [ | |
[0,1,2], [3,4,5], [6,7,8], | |
[0,3,6], [1,4,7], [2,5,8], | |
[0,4,8], [2,4,6] | |
] | |
def initialize() | |
@board = [['','',''], ['','',''], ['','','']] | |
end | |
def move(symbol, x, y) | |
return if (x> 2 || y>2) && !SYMBOLS.include?(symbol) | |
@board[x][y] = symbol | |
end | |
def draw_board | |
@board.each_with_index do |dim1, outer| | |
dim1.each_with_index do |_dim2, inner| | |
print "#{@board[outer][inner]} " | |
end | |
puts | |
end | |
end | |
def check_winner | |
return 'X' if winner?('X') | |
return 'O' if winner?('Y') | |
end | |
private | |
def winner?(symbl) | |
WINNING.any? { |win| win.all? {|pos| fetch_symbol(pos) == symbl } } | |
end | |
def fetch_symbol(index) | |
@board[index%3][index/3] | |
end | |
end | |
ttt = TicTacToeBoard.new | |
ttt.move("X", 0, 0) | |
ttt.move("O", 0, 2) | |
ttt.move("X", 1, 0) | |
ttt.move("O", 1, 2) | |
ttt.move("X", 2, 0) | |
ttt.draw_board # display the board | |
ttt.check_winner # should return the winner, "X" | |
# fptr = File.open(ENV['OUTPUT_PATH'], 'w') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment