Commits

Steven! Ragnarök committed 977ca82

Add Board class.

Comments (0)

Files changed (1)

+# Chess Validator - Board
+# =======================
+#
+# Part of my solution to PuzzleNode #13.
+# Replication of a chess board.
+#   a b c d e f g h
+# 8                 8
+# 7                 7
+# 6                 6
+# 5                 5
+# 4                 4
+# 3                 3
+# 2                 2
+# 1                 1
+#   a b c d e f g h
+class Board
+  BOARD_LETTERS ={ 'a' => 0, 'b' => 1, 'c' => 2, 'd' => 3, 'e' => 4, 'f' => 5,
+                   'g' => 6, 'h' => 7 }
+
+  def initialize input_string
+    @board_matrix = input_string.lines.map &:split
+  end
+
+  def [] index
+    @board_matrix[index]
+  end
+
+  def algebraic? symbol
+   symbol.length == 2 and
+     %w[a b c d e f g h].include? symbol[0] and
+     (1..8).include? symbol[1].to_i
+  end
+
+  def index_from_algebraic symbol
+    [8 - symbol[1].to_i, BOARD_LETTERS[symbol[0]]]
+  end
+
+  def method_missing symbol, *args, &block
+    if algebraic? symbol
+      row, col = index_from_algebraic symbol
+      @board_matrix[row][col]
+    else
+      super symbol, *args, &block
+    end
+  end
+end