On Thu, 27 Oct 2005 21:22:06 +0200, Markus Koenig <markus / stber-koenig.de>  
wrote:

> CBlair1986 wrote:
>
>> I've just got a bit of a question, here. I suppose my mind's a bit too
>> tired to think of a solution at the moment, but it's been on my mind
>> for a while. What I'd like to do is take an array and turn it into an
>> isometric view of the data, eg:
>>
>> [...]
>
> Heh, another Ruby quiz. ;)

Indeed, here is my solution:


class AsciiCanvas

    def initialize
       @dat = []
    end

    def to_s
       @dat.join("\n")
    end

    def draw(str, x, y)
       lines = str.split("\n")
       lines.each_with_index { |l, i|
          cy = y + i
          cl = (@dat[cy] || "")
          cl = cl.ljust(x+l.size)
          cl[x, l.size] = l
          @dat[cy] = cl
       }
    end

end

def make_iso_view(array)
    square = "+-----+\n|     |\n|     |\n+-----+"
    con = "\\     \\\n \n \n\\"

    a = AsciiCanvas.new
    stepx = 6
    stepy = 3
    stepz = 2

    # draw from bottom to top, back to front and right to left
    y = stepy * (array.size - 1)
    array.each { |level|
       ly, lx = y, 0
       level.each { |row|
          ry, rx = ly, lx + stepx * (row.size - 1)
          row.reverse.each { |box|
             unless !box || box == 0
                a.draw(square, rx, ry)
                a.draw(con, rx+1, ry+1)
                a.draw(square, rx+2, ry+2)
             end
             rx -= stepx
          }
          lx += stepz
          ly += stepz
       }
       y -= stepy
    }
    a.to_s
end

if $0 == __FILE__
    puts make_iso_view([[[1,1], [1,1]], [[0,1], [0,0]]])
    puts make_iso_view([[[0,1,1], [1,0,1]], [[0,1,0], [0,0,0]]])
end


Dominik