Trying to implement flood fill algorithm in pygame just as a learning experience. I have a good start I think and it is mostly functional, but after several seconds of working properly, it gives me a max recursion depth error.
import pygame, random, math
from pygame.locals import *
class GameMain():
done = False
color_bg = Color('white')
def __init__(self, width=800, height=800):
pygame.init()
self.width, self.height = width, height
self.screen = pygame.display.set_mode((self.width, self.height))
self.clock = pygame.time.Clock()
def main_loop(self):
while not self.done:
self.handle_events()
self.draw()
self.clock.tick(60)
pygame.quit()
def draw(self):
self.screen.fill(self.color_bg)
pygame.draw.rect(self.screen,Color("grey30"), [100,100,400,300],2)
pygame.draw.rect(self.screen,Color("grey30"), [ 300,300,400,300],2)
pygame.display.flip()
def handle_events(self):
events = pygame.event.get()
# keystates
keys = pygame.key.get_pressed()
# events
for event in events:
if event.type == pygame.QUIT:
self.done = True
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
self.done = True
if event.type == MOUSEBUTTONDOWN:
x,y = pygame.mouse.get_pos()
coord = [x,y]
self.flood_fill(self.screen,coord)
def flood_fill(self,screen,coord):
if screen.get_at((coord[0],coord[1])) == Color("grey30"):
return
screen.set_at((coord[0],coord[1]),Color("grey30"))
pygame.display.flip()
self.flood_fill(self.screen, [coord[0] +1, coord[1]])
self.flood_fill(self.screen, [coord[0] -1, coord[1]])
self.flood_fill(self.screen, [coord[0], coord[1]+1])
self.flood_fill(self.screen, [coord[0], coord[1]-1])
if __name__ == "__main__":
game = GameMain()
game.main_loop()
My program runs for a second or two and changes the color of a few x,y coordinates, but then it goes crazy and I get a recursion depth error. Not sure why it works for a second and then fails.