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坐标的颜色,但随后都疯了,我得到一个递归深度误差。不知道为什么它一秒钟工作,然后失败。
下面是号称保持递归深度浅(我只是GOOGLE了 - 我没有检查)洪水填充变形的链接: http://www.adammil.net/blog/v126_A_More_Efficient_Flood_Fill.html哦这一个看起来更好:http://steve.hollasch.net/cgindex/polygons/floodfill.html –