tictactoe/board.rb

69 lines
1.3 KiB
Ruby
Raw Normal View History

2018-01-23 01:04:38 +00:00
class Array
def same_values?
self.uniq.length == 1
end
def contains? x
self.include? x
end
end
class Board
attr_reader :spaces, :def_val
def initialize
@def_val = "---"
@spaces = Array.new(9, @def_val)
end
def to_s
"|#{@spaces[0]}|#{@spaces[1]}|#{@spaces[2]}|
-------------
|#{@spaces[3]}|#{@spaces[4]}|#{@spaces[5]}|
-------------
|#{@spaces[6]}|#{@spaces[7]}|#{@spaces[8]}|
-------------"
end
def get_free
@spaces.each_index.select { |s| @spaces[s] == @def_val }
end
def set val, idx
@spaces[idx] = val
end
def remove idx
@spaces[idx] = @def_val
end
def any_winner?
winning_combos = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
winning_combos.each do |s|
tmp = s.map {|i| @spaces[i]}
if (not tmp.include? @def_val) and tmp.same_values? then
return true
end
end
return false
end
def is_winner? player
winning_combos = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
winning_combos.each do |s|
tmp = s.map {|i| @spaces[i]}
if (not tmp.include? @def_val) and tmp.same_values? and tmp[0] == player then
return true
end
end
return false
end
def is_full?
get_free.empty?
end
end