Python中的边缘检测

2024-04-19 18:20:45 发布

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

我试着写一个程序,用户输入一个数字,它在屏幕上画出那么多的矩形,但是三角形不能重叠。我对最后一部分有问题,我正在寻求帮助。我借用了Al-Sweigart的一本书中的边缘检测方法,他编写的完整程序可以在这里找到:

http://inventwithpython.com/chapter18.html

以下是我正在执行的程序:

http://pastebin.com/EQJVH6xr

import pygame, sys, random
from pygame.locals import *

def doRectsOverlap(rect1, rect2):
    for a, b in [(rect1, rect2)]:
        # Check if a's corners are inside b
        if ((isPointInsideRect(a.left, a.top, b)) or
            (isPointInsideRect(a.left, a.bottom, b)) or
            (isPointInsideRect(a.right, a.top, b)) or
            (isPointInsideRect(a.right, a.bottom, b))):
            return True

    return False

def isPointInsideRect(x, y, rect):
    if (x > rect.left) and (x < rect.right) and (y > rect.top) and (y < rect.bottom):
        return True
    else:
        return False

# set up pygame
pygame.init()

# set up the window
WINDOWWIDTH = 600
WINDOWHEIGHT = 600
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Rectangles')

# set up the colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

from random import choice
foo = [BLACK, RED, GREEN, BLUE]

# draw the background
windowSurface.fill(WHITE)

print('Please enter a number:')
number = input()
x = 0
array = []
for i in array:

while int(number) > x:
    x = x+1
    x1 = random.randint(1, 400)
    y1 = random.randint(1, 400)
    x2 = random.randint(1, 400)
    y2 = random.randint(1, 400)
    x3 = random.randint(1, 400)
    y3 = random.randint(1, 400)
    x4 = random.randint(1, 400)
    y4 = random.randint(1, 400)
    box = pygame.draw.rect(windowSurface,random.choice(foo), (x1, y1, x2, y2))
    if doRectsOverlap(box, box) == False:
        box
    else:
        x = x-1

# draw the window onto the screen
pygame.display.update()

任何帮助都将不胜感激。谢谢您!在


Tags: ortherectimport程序boxreturnif
1条回答
网友
1楼 · 发布于 2024-04-19 18:20:45

作为一个一般的答案,你需要为每个长方形画出四个共同法则。在

有几种方法可以做到:

1)只需将矩形随机放置并测试新矩形的任何点是否位于任何现有矩形的内部。如果是的话,继续生成直到它们不存在。但这将是非常缓慢和低效的。在

2)你可以把所有可能的随机数限制在可用的位置上。这是可以通过多种方式实现的,它将是半缓慢的,并且可能相当难以实现。在

3)可以像选项1一样生成矩形,但如果4个点的co条例重叠,则可以将这些点推掉。要做到这一点,你只需将违反的co条例设置为其中一个角的co条例,然后加上,比如,(5,5)或减法或其他任何东西。如果不想使矩形倾斜太多,可以基于修改的点重新生成违规矩形,或者将所有点推到与违规点相等的距离。在

我认为方案3可能是最好的,除非你对随机原则非常严格。在

如果你想让我澄清以上任何一个选项,请让我具体地知道你想让我解释什么,我会这样做的。然而,我无法解释每个选项的所有可能性,因为它需要很长的时间和太多的行。在

干杯

相关问题 更多 >