gpt4 book ai didi

python - Python 中的边缘检测

转载 作者:太空宇宙 更新时间:2023-11-03 18:37:38 24 4
gpt4 key购买 nike

我正在尝试编写一个程序,用户输入一个数字,它会在屏幕上绘制许多矩形,但是三角形不能重叠。我在最后一部分遇到了问题,我正在寻求帮助。我借用了 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()

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

最佳答案

作为一般答案,您必须为每个矩形绘制四个坐标。

有几种方法可以做到这一点:

1) 只需随机放置矩形并测试新矩形的任何点是否位于任何现有矩形的内部。如果是,就继续生成,直到不再。但这会非常缓慢且效率低下。

2) 您可以通过将所有可能的随机数限制为仅可用的位置来进行数字压缩。这可以通过多种方式完成,但速度会很慢,而且可能相当难以实现。

3) 您可以像选项 1 一样生成矩形,但在 4 个点的坐标重叠的情况下,您可以将这些点推开。为此,您只需将违规坐标设置为其中一个角的坐标,然后添加(5,5)或减去或其他。如果您不想使矩形倾斜太多,您可以根据修改的点重新生成违规矩形,或者将所有点插入与违规点相等的距离。

我认为选项 3 可能是最好的,除非您对随机原则非常严格。

如果您希望我澄清上述任何选项,请具体告诉我您希望我解释什么,我会这样做。然而,我无法解释每个选项的所有可能性,因为它会花费很长且太多的行。

干杯

关于python - Python 中的边缘检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21248429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com