Created
April 14, 2018 18:08
-
-
Save pskl/df5960f3fa823fc0a9cd9eb6ffdb1c36 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 'terminal-table' | |
def play(board_size:) | |
@board = Array.new(board_size.to_i) { Array.new(board_size.to_i) } | |
while true | |
break if [:p1, :p2️].any? { |s| turn(s) } | |
end | |
puts [email protected]? ? "#{@winner} 💫" : "draw 😒" | |
end | |
def turn(symbol) | |
puts symbol | |
puts Terminal::Table.new(rows: @board) | |
input = STDIN.gets.chomp | |
x , y = input.split(",").map(&:to_i) | |
while /\d,\d/.match(input).nil? && !@board[x][y].nil? | |
puts '❌' | |
input = STDIN.gets.chomp | |
end | |
@board[x][y] = symbol | |
return true if (row_win? || column_win? || diagonal_win? || @board.all? { |row| !row.include?(nil) } ) | |
end | |
def row_win? | |
@board.each { |row| return @winner = row[0] if row.uniq.length == 1 && !row[0].nil? } | |
false | |
end | |
def column_win? | |
([email protected] - 1).each { |index| return @winner = @board[0][index] if @board.map { |r| r[index] }.uniq.length == 1 && !@board[0][index].nil? } | |
false | |
end | |
def diagonal_win? | |
return @winner = @board[0][0] if ([email protected] - 1).map { |index| @board[index][index] }.uniq.length == 1 && !@board[0][0].nil? | |
return @winner = @board[-1][-1] if ([email protected] - 1).map { |index| @board[@board.length - 1][@board.length - 1 - index] }.uniq.length == 1 && !@board[-1][-1].nil? | |
false | |
end | |
play(board_size: ARGV[0]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment