Diwakar
Diwakar

Reputation: 73

flood fill algorithm crashing in python

I am trying to fill color in a polygon using the flood fill recursive algorithm. I am coding in python 2.7. I goes halfway towards the filling then crashes. It happens all the time I run the code. Is there any thing wrong with the code or it's just the problem in my laptop. Please help? Thank you. Here is the code.

    import pygame
    import numpy as np
    from pygame.locals import *
    import sys
    def flood_fill(name, x, y, color):
        get = name.get_at((x, y))
        if get == (0, 0, 0, 255):
            screen.set_at((x, y), red)
            pygame.display.flip()
            flood_fill(name, x + 1, y, color)
            flood_fill(name, x - 1, y, color)
            flood_fill(name, x, y + 1, color)
            flood_fill(name, x, y - 1, color)

   if __name__ == '__main__':
        pygame.init()
        sys.setrecursionlimit(1500000000)
        width = 640
        height = 480
        resolution = (width, height)
        screen = pygame.display.set_mode(resolution)
        black = (0, 0, 0)
        white = (255, 255, 255)
        red = (255, 0, 0)
        pygame.draw.rect(screen, white, [20, 20, 250, 100], 2)
        flood_fill(screen, 100, 50, red)
        while True:
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
            pygame.display.flip()

Upvotes: 0

Views: 855

Answers (2)

Eelco Hoogendoorn
Eelco Hoogendoorn

Reputation: 10759

Pretty sure your recursion limit is the problem. All setrecursionlimit does really is remove the warnings that would prevent you from doing stupid things; it does not magically create the transistors in your CPU to hold a 1500000000 call stack.

Implementing a floodfill on the stack is generally speaking a bad idea. Use a stack datastructure in a while loop instead.

Upvotes: 1

pkacprzak
pkacprzak

Reputation: 5629

You should provide the error that you are getting, but based on the code, I think that the error is the IndexError and you should check if pixel coordinates are valid coordinates i.e. they always are inside the area of the surface which is in your case the screen.

According to the documentation: If the pixel position is outside the area of the Surface an IndexError exception will be raised.

Just make sure, that get_at method gets valid parameters or surround it with the try\except block.

Upvotes: 0

Related Questions