Search code examples
pythonconsoleconsole-applicationanimated

Animate flood fill in python


I have just finished with my food fill algorithm in python. It runs on an N*N matrix filled with integers. I would like to somehow animate it's workings. Is it somehow possible on the console? I think of something like updateing the nodes with a wait() inbetween the updates.


Solution

  • You could use something like this:

    #! /usr/bin/python3
    import time
    
    m = [ [c for c in line] for line in '''............................
    ..XXXXXXXXXX...........XXX..
    ..X........X...........X.X..
    ..XXXXXX...X....XXXXXXXX.X..
    .......X...X....X........X..
    ....XXXX...XXXXXX........X..
    ....X....................X..
    ....X.................XXXX..
    ....XXXXXXXXXXXXXXXXXXX.....'''.split ('\n') ]
    
    def flood (matrix, start):
        maxX = len (matrix [0] )
        maxY = len (matrix)
        tbf = [start]
        while tbf:
            x, y = tbf [0]
            tbf = tbf [1:]
            if x < 0 or x >= maxX or y < 0 or y >= maxY: continue
            if matrix [y] [x] == 'X': continue
            matrix [y] [x] = 'X'
            tbf += [ (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1) ]
            print ('\x1b[0J\x1b[1;1H') #Clear screen and position cursor top left
            for line in matrix: print (''.join (line) )
            time.sleep (.2)
    
    #flood (m, (0, 0) )
    flood (m, (4, 2) )
    

    This should work on any console that supports ANSI escape sequences (CSI). You can use the same CSI codes for outputting colours (Wiki).