tictactoe/board.rb

68 lines
1.2 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
2018-01-23 01:43:28 +00:00
attr_reader :spaces, :def_val, :winning_scens
2018-01-23 01:04:38 +00:00
def initialize
2018-01-23 01:43:28 +00:00
@def_val = " "
2018-01-23 01:04:38 +00:00
@spaces = Array.new(9, @def_val)
2018-01-23 01:43:28 +00:00
@winning_scens = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
2018-01-23 01:04:38 +00:00
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?
2018-01-23 01:43:28 +00:00
@winning_scens.each do |s|
2018-01-23 01:04:38 +00:00
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
2018-01-23 01:43:28 +00:00
@winning_scens.each do |s|
2018-01-23 01:04:38 +00:00
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