2017-04-01 23 views
0

试图在pygame中实现洪水填充算法,就像学习体验一样。我有一个很好的开始,我认为它主要是功能性的,但经过几秒钟的正常工作,它给我一个最大递归深度错误。洪水填充算法,工作几秒钟,但然后出错。 (pygame)

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() 

我的计划,第二运行或两个,并改变了几x,y坐标的颜色,但随后都疯了,我得到一个递归深度误差。不知道为什么它一秒钟工作,然后失败。

+0

下面是号称保持递归深度浅(我只是GOOGLE了 - 我没有检查)洪水填充变形的链接: http://www.adammil.net/blog/v126_A_More_Efficient_Flood_Fill.html哦这一个看起来更好:http://steve.hollasch.net/cgindex/polygons/floodfill.html –

回答

0

Python不是特别设计或倾向于递归操作。在CPython实现中,递归深度限于。

您可以通过检查:

import sys 
print(sys.getrecursionlimit()) 

因此,您可以覆盖使用sys.setrecursionlimit()而不是限制。

但是,这不是特别安全/最好的选择。

您最好重写代码以实现迭代。


编辑:道歉,我意识到我没有指出,你应该看看代码。

递归实际发生在您的flood_fill()方法中,因为它实际上再次调用self.floor_fill()四(4)次。


欲了解更多信息,可以阅读起来:http://seriously.dontusethiscode.com/2013/04/14/setrecursionlimit.html