Last active
March 26, 2016 02:53
-
-
Save ricardotealdi/797f25e4020c5f8e8aff to your computer and use it in GitHub Desktop.
tic tac toe
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
# Usage: ruby -e "$(curl -s https://gist.githubusercontent.com/ricardotealdi/797f25e4020c5f8e8aff/raw/<HASH>/tictactoe.rb)" | |
board_add = -> (board, x, y, piece) { board[y][x] ? nil : board[y][x] = piece } | |
board_print = lambda do |board| | |
puts "" | |
puts ' 1 2 3' | |
board.each_with_index do |row, index| | |
format_row = row.map { |it| it.nil? ? ' ' : it.to_s.upcase }.join ' | ' | |
puts( | |
" #{index + 1} #{format_row} " | |
) | |
puts " #{"-" * 11} " if index < 2 | |
end | |
puts "" | |
end | |
board_full = -> (board) { board.all? { |row| row.none?(&:nil?) } } | |
board_winner_horizontally = lambda do |board| | |
winner_row = board.detect { |row| row.uniq.size == 1 } | |
winner_row && winner_row.first | |
end | |
board_winner_vertically = lambda do |board| | |
winner_column = (0..2).to_a.detect do |row| | |
(0..2).to_a.map { |column| board[column][row] }.uniq.size == 1 | |
end | |
winner_column && board[0][winner_column] | |
end | |
board_winner_transversely = lambda do |board| | |
winner_column = [0, 2].detect do |column| | |
(0..2).map { |index| board[index][(-(column) + index).abs] }.uniq.size == 1 | |
end | |
winner_column && board[0][winner_column] | |
end | |
board_winner = lambda do |board| | |
board_winner_horizontally.call(board) || | |
board_winner_vertically.call(board) || | |
board_winner_transversely.call(board) | |
end | |
board_finished = lambda do |board| | |
winner = board_winner.call(board) | |
return winner if winner | |
board_full.call(board) ? :tie : nil | |
end | |
game = lambda do | |
players = %i(X O).shuffle | |
turn = 0 | |
board = Array.new(3) { |it| it = Array.new(3) } | |
while !(result = board_finished.call(board)) | |
system('clear') | |
board_print.call(board) | |
current_player = players[turn % 2] | |
puts "Turn: #{turn}" | |
puts "Player: #{current_player}" | |
begin | |
puts "Choose your position (X):" | |
x = gets.strip.to_s.to_i - 1 | |
end until x >= 0 && x <= 2 | |
begin | |
puts "Choose your position (Y):" | |
y = gets.strip.to_s.to_i - 1 | |
end until y >= 0 && y <= 2 | |
next unless board_add.call(board, x, y, current_player) | |
turn += 1 | |
end | |
system('clear') | |
board_print.call(board) | |
puts "The winner is: #{result}" | |
end | |
game.call |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment