這個函式應該找出視窗內是否有超過一定數量的點,如果在它周圍繪制一個矩形,然后通過在前一個矩形的所有四個象限上遞回呼叫相同的函式來細分。對于前 2 次遞回,這種行為似乎幾乎是正確的,然后似乎有點不對勁。我還設定了一個最大深度,這樣它就不會遞回太久。我使用 pygame 在螢屏上繪制矩形。我假設我在某個地方的邏輯混亂了。
def recursion(x,x2,y,y2,max):
#draws a square
pygame.draw.rect(screen,(0,255,255),(x,y,x2,y2),1)
currentMax = 0
total_points = 0
if max >= 30:
return None
currentMax = max 1
for i in range(len(xlist)):
if xlist[i] in range(x,x2) and ylist[i] in range(y,y2):
total_points = 1
if total_points > 3:
recursion(int(x),int(x2/2),int(y),int(y2/2),currentMax)#top_left
recursion(int(x2/2),int(x2),int(y),int(y2/2),currentMax)#top_right
recursion(int(x),int(x2/2),int(y2/2),int(y2),currentMax)#bottom_left
recursion(int(x2/2),int(x2),int(y2/2),int(y2),currentMax)#bottom_right
我還呼叫它一次以開始遞回:
recursion(int(0),int(1000),int(0),int(1000),0)
這些點是使用以下方法生成的:
for i in range(5):
xlist.append(random.randint(0,1000))
ylist.append(random.randint(0,1000))
uj5u.com熱心網友回復:
繪制矩形時,
import pygame, random
pygame.init()
screen = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()
def recursion(x,x2,y,y2,depth):
if depth >= 5:
return
depth = 1
total_points = 0
for i in range(len(xlist)):
if x < xlist[i] <= x2 and y < ylist[i] <= y2:
total_points = 1
if total_points >= 1:
pygame.draw.rect(screen, (0,255,255), (x, y, x2-x, y2-y), 1)
centerx = (x x2) // 2
centery = (y y2) // 2
recursion(x, centerx, y, centery, depth)
recursion(centerx, x2, y, centery, depth)
recursion(x, centerx, centery, y2, depth)
recursion(centerx, x2, centery, y2, depth)
xlist = []
ylist = []
for i in range(5):
xlist.append(random.randrange(screen.get_width()))
ylist.append(random.randrange(screen.get_height()))
screen.fill(0)
recursion(0, screen.get_width(), 0, screen.get_height(), 0)
for p in zip(xlist, ylist):
pygame.draw.circle(screen, (255, 0, 0), p, 8)
pygame.display.flip()
#pygame.image.save(screen, "grid.png")
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.flip()
clock.tick(60)
pygame.quit()
exit()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/489057.html
上一篇:可以模擬遞回CTE嗎?
下一篇:子值的SQL樹遞回平均值
