Skip to content

Instantly share code, notes, and snippets.

/ttt.rb Secret

Created January 10, 2016 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/0880665f4f7d311d9273 to your computer and use it in GitHub Desktop.
Save anonymous/0880665f4f7d311d9273 to your computer and use it in GitHub Desktop.
Tic Tac Toe in Ruby
# NOT FINISHED!
class Board
HORIZONTAL_ROWS = (0..8).each_slice(3).to_a
VERTICAL_ROWS = HORIZONTAL_ROWS.transpose
DIAGONAL_ROWS = [
HORIZONTAL_ROWS.each_with_index.map {|a, i| a[i] },
HORIZONTAL_ROWS.each_with_index.map {|a, i| a[2-i] },
]
def initialize
@board = Array.new(9)
end
def set_pos(pos, sym)
idx = pos - 1
if @board[idx].nil?
@board[idx] = sym
else
raise 'Position already taken'
end
end
def three_in_a_row?(sym)
(HORIZONTAL_ROWS + VERTICAL_ROWS + DIAGONAL_ROWS) \
.any? {|x| elems_eq_sym?(x, sym) }
end
def elems_eq_sym?(idxs, sym)
idxs
.map {|i| @board.at(i) }
.all? {|e| e == sym }
end
def to_s
hr = "+---+---+---+\n"
str = @board
.each_with_index.map {|x, i| x.nil? ? "#{i+1} " : " #{x.to_s.upcase} " }
.each_slice(3).map {|a| "|#{a.join('|')}|\n" }
.join(hr)
hr + str + hr
end
end
module TicTacToe
Player = Struct.new(:name, :symbol)
PLAYERS = [
Player.new('Player 1 (X)', :x),
Player.new('Player 2 (O)', :o),
]
def self.play
board = Board.new
PLAYERS.cycle do |p|
puts board
print "#{p.name}, choose a position: "
pos = gets.to_i
board.set_pos(pos, p.symbol)
# ...
if board.three_in_a_row?(p.symbol)
puts "#{p.name} won!"
break
end
end
end
end
TicTacToe.play
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment