state = {}
sprites = {}

difficulty = 5;

function random_color()
   local choices = {'red', 'green', 'blue'}
   return choices[math.floor(math.random() * 3 + 1)]
end

function love.load()
   state.t = 0
   state.frame = 0
   state.board = {}

   local choices = {'red', 'green', 'blue'}
   for x = 0, 7 do
      state.board[x] = {}
      for y = 0, 15 do
         local choice = math.floor(math.random() * 6)
         if y < difficulty then
            state.board[x][y] = choices[choice]
         else
            state.board[x][y] = nil
         end
      end
   end

   for _, color in pairs({'red', 'green', 'blue'}) do
      sprites[color] = {}
      for n = 0, 9 do
         sprites[color][n] =
            love.graphics.newImage('sprites/' .. color .. '_' .. n .. '.png')
      end
      sprites[color]['pill'] =
         love.graphics.newImage('sprites/pill_' .. color .. '.png')
   end

   love.window.setMode(8 * 24, 16 * 24)
end

function love.update()
   state.t = state.t + 1
   if state.t % 2 == 0 then
      state.frame = state.frame + 1
   end
   if state.t % 64 == 0 then
      if state.current then
         state.current[1][3] = state.current[1][3] - 1
         state.current[2][3] = state.current[2][3] - 1
      else
         state.current = {{random_color(), 3, 15, 'l'},
            {random_color(), 4, 15, 'r'}}
      end
   end
end

function love.keypressed(key)
   if key == 'q' then
      love.event.quit()
   elseif key == 'left' and state.current and state.current[1][2] > 0 then
      state.current[1][2] = state.current[1][2] - 1
      state.current[2][2] = state.current[2][2] - 1
   elseif key == 'right' and state.current and state.current[1][2] < 7 then
      state.current[1][2] = state.current[1][2] + 1
      state.current[2][2] = state.current[2][2] + 1
   elseif key == 'down' and state.current then
      state.current[1][3] = state.current[1][3] - 1
      state.current[2][3] = state.current[2][3] - 1
   end
end

function rot(x, y, r)
   if r == 'u' then
      return x, y, 0
   elseif r == 'r' then
      return x + 24, y, (math.pi / 2)
   elseif r == 'd' then
      return x + 24, y + 24, math.pi
   elseif r == 'l' then
      return x, y + 24, math.pi * 1.5
   end
end

function love.draw()
   love.graphics.setColor(255, 255, 255)
   love.graphics.rectangle('fill', 0, 0, 8 * 24, 16 * 24)

   for x = 0, 7 do
      for y = 0, 15 do
         local c = state.board[x][y]
         if c then
            love.graphics.draw(sprites[c][state.frame % 10], x * 24, (24 * 15) - y * 24)
         end
      end
   end

   if state.current then
      for _, p in pairs(state.current) do
         local x, y, r = rot(p[2] * 24, (24 * 15) - p[3] * 24, p[4])
         love.graphics.draw(sprites[p[1]]['pill'], x, y, r)
      end
   end
end
