Created
January 14, 2016 20:01
-
-
Save mindplace/a5a378cf9895498ffe81 to your computer and use it in GitHub Desktop.
board class for tic tac toe
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
class Board | |
def initialize(grid=[[nil, nil, nil], [nil, nil, nil], [nil, nil, nil]]) | |
@grid = grid | |
end | |
def grid | |
@grid | |
end | |
def place_mark(position, symbol) | |
row = position[0] | |
column = position[1] | |
@grid[row][column] = symbol | |
end | |
def empty?(position) | |
row = position[0] | |
column = position[1] | |
@grid[row][column].nil? | |
end | |
def place_marks(positions, symbol) | |
postions.each do |position| | |
place_mark(position, symbol) | |
end | |
end | |
def over? | |
if @grid.flatten.count(nil) == 0 | |
true | |
elsif winner == :X || winner == :O | |
true | |
else | |
false | |
end | |
end | |
def sets | |
return nil if @grid.flatten.count(nil) == 0 | |
row_set = [] | |
if @grid.any?{|row| row.count(:X) == 3} | |
row_set << grid.select{|row| row.count(:X) == 3} | |
elsif @grid.any?{|row| row.count(:O) == 3} | |
row_set << grid.select{|row| row.count(:X) == 3} | |
end | |
return row_set.flatten.pop unless row_set.flatten.empty? | |
first_column = [] | |
second_column = [] | |
third_column = [] | |
@grid.each do |row| | |
first_column << row[0] | |
second_column << row[1] | |
third_column << row[2] | |
end | |
diagonal_set_backslash = [@grid[0][0], @grid[1][1], @grid[2][2]] | |
diagonal_set_forward = [@grid[0][2], @grid[1][1], @grid[2][0]] | |
if first_column.count(:O) == 3 || first_column.count(:X) == 3 | |
first_column.flatten.pop | |
elsif second_column.count(:O) == 3 || second_column.count(:X) == 3 | |
second_column.flatten.pop | |
elsif third_column.count(:O) == 3 || third_column.count(:X) == 3 | |
third_column.flatten.pop | |
elsif diagonal_set_backslash.count(:O) == 3 || diagonal_set_backslash.count(:X) == 3 | |
diagonal_set_backslash.flatten.pop | |
elsif diagonal_set_forward.count(:O) == 3 || diagonal_set_forward.count(:X) | |
diagonal_set_forward.flatten.pop | |
end | |
end | |
def winner | |
sets | |
end | |
end | |
def preps_grid_for_rendering(board) | |
sets = board.map do |row| | |
row = row.map do |slot| | |
slot = " " if slot.nil? | |
end | |
end | |
#grid = grid.gsub(" ", nil) | |
sets | |
end | |
def display(board) | |
rows = preps_grid_for_rendering(board) | |
puts " | 0 | 1 | 2 " | |
puts " ___________" | |
puts "0| #{rows[0][0]} | #{rows[0][1]} | #{rows[0][2]}" | |
puts "1| #{rows[1][0]} | #{rows[1][1]} | #{rows[1][2]}" | |
puts "2| #{rows[2][0]} | #{rows[2][1]} | #{rows[2][2]}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment