洪水填充算法,工作了几秒钟,然后出错了。(皮加梅)

2024-05-15 01:36:42 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试在pygame中实现flood-fill算法作为一种学习体验。我有一个很好的开始,我认为它基本上是功能性的,但经过几秒钟的正常工作,它给了我一个最大递归深度错误。你知道吗

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坐标的颜色,但后来它变得疯狂,我得到了一个递归深度错误。不知道为什么它能工作一秒钟然后就失败了。你知道吗


Tags: selfeventifdefeventswidthfillscreen
1条回答
网友
1楼 · 发布于 2024-05-15 01:36:42

Python并不是特别设计或倾向于递归操作。在CPython实现中,递归深度限制为1000。你知道吗

您可以通过以下方式进行检查:

import sys
print(sys.getrecursionlimit())

因此,您可以使用sys.setrecursionlimit()来替代限制。你知道吗

然而,这并不是特别安全/最好的选择。你知道吗

你最好重写你的代码来实现一个迭代的实现。你知道吗


编辑:抱歉,我意识到我没有指出您应该查看代码的位置。

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


有关更多信息,请阅读:http://seriously.dontusethiscode.com/2013/04/14/setrecursionlimit.html

相关问题 更多 >

    热门问题