[Tutor] ASCII art generator

Michael Janssen Janssen@rz.uni-frankfurt.de
Sun Feb 2 14:11:02 2003


On Sun, 2 Feb 2003, Michael Miller wrote:

> I realise that this is a rather brute force method of doing this, but I just
> don't have the skill to make anything more elegant. Any idea on how to do so,

Sometimes I narrow my eyes and look crossover the code, it helps me to
visually detect inelegant (and possibly unpythonic - huhu ;-) parts. The
core function ascgen is pretty long and looks desintegrated.

To make it shorter you can take out the logic for transforming the
im.getpixel([x, y]) return value into a string suiteable for a html-color
(this is especially a good idea, because you might change this part in the
future; perhaps you want to test if css-style colors are faster than
font-tags.). Alos you can correct more easily possibly mistakes and at
last: you can provide a docstring for this part. And now the very last
advantages: you can reuse this common function.

The while loop doesn't even look desintegrated. You provide (x < width) as
the condition, but this is never false, because you catch it with the
if-clause condition (x == width). You can change the while condition to 1,
but the whole while-if-if construct lacks a bit readability.

Let's see.. What you want to do is to iterate trough every line. This
means: line-by-line and inside one line "pixel"-by-"pixel". This means you
need two for loops: The first iterates over the lines of the picture (I
call this the outer iteration) and the second iterates over any pixel of
any line:

    for y in range(height):  outer: line-by-line
        for x in range(width): inner each line

since this mailing list is called "tutor", I leave you with this hints.
It's fun to work it out yourself (ehhm in python it is fun :-).

A little note on lists and tuples:
        value = im.getpixel([x, y])
        vallist = list(value) # you just needn't this step: tuple can be
                              # indexed in the same way as lists.
        r = vallist[0]
        g = vallist[1]
        b = vallist[2]
        out = '<FONT color="','#%02X%02X%02X'%(r,g,b),'">'\
               +makerand(),'</FONT>\n'

You can even write (because for string-formatting you need tuples...):
out = '<FONT color="','#%02X%02X%02X' % im.getpixel([x, y])\
         ,'">'+makerand(),'</FONT>\n'

That's good, isn't it?

Michael