def play()
  b = rand_board()
  while not solvable?(b) do
    b = rand_board()
  end
  play_with_board(b)
end

def play_with_board(b)
  Canvas.init(200, 200, "LightsOut")
  display(b)
  puts "Turn all of the lights black."

  while not all_out?(b) do
    row = input_num("Enter row (0-4): ")
    col = input_num("Enter column (0-4): ")
    select!(b, row, col)
    display(b)
  end

  puts "You won!"
  return nil
end

def input_num(prompt)

  while true do
    # get a line from the user and chomp off the newline char
    s = Readline::readline(prompt).chomp

    # stop the program if the user types quit
    raise "quit" if s == "quit"

    # return the number 0-4 as appropriate
    return 0 if s == "0"
    return 1 if s == "1"
    return 2 if s == "2"
    return 3 if s == "3"
    return 4 if s == "4"

    # otherwise print an error message and repeat
    print "Invalid Coordinate.  Try again.", "\n"
  end

end


# This is a stub, you will need to replace this function
# with a complete implementation
def rand_board()
  return nil
end


# This is a stub, you will need to replace this function
# with a complete implementation
def display(board)
  return nil
end


# This is a stub, you will need to replace this function
# with a complete implementation
def select!(board, i, j)
  return nil
end


# This is a stub, you will need to replace this function
# with a complete implementation
def all_out?(board)
  return false
end


# based on http://www.jaapsch.net/puzzles/lights.htm#quiet
#
# There are three "quiet pattern", such that
# selecting all of their tiles leaves the board
# unchanged.  One of which is the composition of the
# other two, which are rotations of each other.  
#
# The two base patterns consist of the positions specified from
# the rows and columns in the arrays qp1 and qp2, respectively.  
# A board is solvable if and only if the number of tiles in 
# each of qp1 and qp2 is even.

def solvable?(board)

  qp1 = [[0,0],[1,0],[3,0],[4,0],
         [0,2],[1,2],[3,2],[4,2],
         [0,4],[1,4],[3,4],[4,4]]
 
  qp2 = [[0,0],[0,1],[0,3],[0,4],
         [2,0],[2,1],[2,3],[2,4],
         [4,0],[4,1],[4,3],[4,4]]

  # This is an incomplete implementation of solvable
  # You should add code _below_ so that solvable? returns 
  # false if 
  #    (a) an odd number of the elements in board at
  #        the positions specified by qp1 are lit, or
  #    (b) an odd number of the elements in board at 
  #        the position  specified by qp2 are lit.
  #
  # This should be accomplished with loops that use the
  # [row,column] pairs in qp1 and qp2 to determine whether
  # the lights are on in each indicated position.  
  #
  # If you can't solve this problem using the two arrays
  # and loops, but you can solve the problem by counting
  # each position individually, you will ear 1 of the 2 
  # points.
  #
  # Complete this function here:


  return true
end
