aboutsummaryrefslogtreecommitdiffstats
path: root/board.rb
diff options
context:
space:
mode:
authorTeddy Wing2015-04-16 02:13:04 -0400
committerTeddy Wing2015-04-16 02:13:04 -0400
commit6984fc31370564332ceab60c203cd6f1e695d61a (patch)
treea53d6b3ecf3c1ba4f35fcd245c30757e1a266e11 /board.rb
parentfa951e520b7637d9e67c31a0a8b61733e253f90b (diff)
parent93351518faf3bb4f63b4a3cc1ef28f5c06e09f01 (diff)
downloadtic-tac-toe-master.tar.bz2
Merge branch 'rspec-style'HEADmaster
Diffstat (limited to 'board.rb')
-rw-r--r--board.rb75
1 files changed, 75 insertions, 0 deletions
diff --git a/board.rb b/board.rb
new file mode 100644
index 0000000..4bef0d3
--- /dev/null
+++ b/board.rb
@@ -0,0 +1,75 @@
+class Board
+ attr_accessor :current_player
+
+ def initialize
+ @board = [
+ ['.', '.', '.'],
+ ['.', '.', '.'],
+ ['.', '.', '.']
+ ]
+ end
+
+ def render
+ output = ''
+ @board.each {|row| output << row.join + "\n" }
+ output
+ end
+
+ # Raises an ArgumentError if integer conversion fails
+ def transform_coordinates(str)
+ coordinates = str.split(',')
+
+ begin
+ coordinates[0] = Integer(coordinates[0])
+ coordinates[1] = Integer(coordinates[1])
+
+ coordinates if coordinates.length > 1
+ rescue
+ end
+ end
+
+ def update_cell(row_index, column_index, value)
+ @board[row_index][column_index] = value
+ end
+
+ def winner?
+ initial = '.'
+
+ # Check horizontal
+ @board.each do |row|
+ return row[0] if array_items_equal(row) and row[0] != initial
+ end
+
+ # Check vertical
+ @board.transpose.each do |column|
+ return column[0] if array_items_equal(column) and column[0] != initial
+ end
+
+ # Check diagonals
+ descending = [
+ @board[0][0],
+ @board[1][1],
+ @board[2][2]
+ ]
+ if array_items_equal(descending) and descending[0] != initial
+ return descending[0]
+ end
+
+ ascending = [
+ @board[2][0],
+ @board[1][1],
+ @board[0][2]
+ ]
+ if array_items_equal(ascending) and ascending[0] != initial
+ return ascending[0]
+ end
+
+ nil
+ end
+
+ private
+
+ def array_items_equal(arr)
+ arr.uniq.length == 1
+ end
+end