2014-09-13 131 views
1

我有一段代碼應該在屏幕上放置1000個正方形,沒有重疊。pygame碰撞檢測工作不正常

但是當我運行它時,我只是得到一堆正方形,其中一些正方形重疊,任何想法我錯了?

import time, pygame, ctypes, random 

class Block(pygame.sprite.Sprite): 
    def __init__(self, color, width, height): 
     pygame.sprite.Sprite.__init__(self) 
     self.image = pygame.Surface([width, height]) 
     self.image.fill(color) 
     self.rect = self.image.get_rect() 

white = (255,255,255) 
black = (0, 0, 0) 
user32 = ctypes.windll.user32 
sw = user32.GetSystemMetrics(0) 
sh = user32.GetSystemMetrics(1) 

Bloqs = {} 
#Bloq atributes: Position (upper left), Size, Color, Genetics 

pygame.init() 
all_sprites_list = pygame.sprite.Group() 

def Collision(bloq): 
    global all_sprites_list 
    hit = pygame.sprite.spritecollide(bloq, all_sprites_list, True) 
    if len(hit) == 0: 
     return False 
    if len(hit) > 0: 
     return True 

def InitializeSim(): 
    global Bloqs 
    global white 
    global black 
    global sw 
    global sh 
    global all_sprites_list 

    size = sw, sh 
    screen = pygame.display.set_mode(size, pygame.FULLSCREEN) 
    screen.fill(white) 
    count = 0 
    while count < 1000: 
     size = 10 
     pos = random.seed() 
     posx = random.randint(0, sw-size) 
     posy = random.randint(0, sh-size) 
     #pygame.draw.rect(screen, color, (x,y,width,height), thickness) 
     CurrentBloq = "bloq" + str(count) 
     Bloqs[CurrentBloq]={} 
     Bloqs[CurrentBloq]["position"] = (sw, sh) 
     bloq = Block(black, size, size) 
     bloq.rect.x = posx 
     bloq.rect.y = posy 
     Bloqs[CurrentBloq]["sprite"] = bloq 
     all_sprites_list.add(bloq) 
     all_sprites_list.draw(screen) 
     pygame.display.update() 
     while Collision(bloq) == True: 
      all_sprites_list.remove(bloq) 
      posx = random.randint(0, sw-size) 
      posy = random.randint(0, sh-size) 
      bloq.rect.x = posx 
      bloq.rect.y = posy 
      all_sprites_list.add(bloq) 
      all_sprites_list.draw(screen) 
      pygame.display.update() 
     count += 1 

InitializeSim() 
time.sleep(5) 
pygame.quit() 

回答

1

您的代碼似乎是你正在嘗試做的相當複雜......然而

方法它作爲一個整體感覺自然給你,但產生的塊時,我會按照沿東西越行:

for i in range(numberofblocksyouwant): 

    while true: 
     create a block at a random x,y pos 
     if block collides with any existing blocks: 
      remove the block you just created 
     else: 
      break 

對於你希望每一個塊,這種方法會繼續重建每一個塊,直到它選擇一個隨機的x,y,不結束與任何其他塊碰撞。

但是,如果你的塊填滿了屏幕並且做不可能,嵌套的while循環將永遠不會結束。

希望有幫助,讓我知道如果沒有任何意義。

1

要建立在最大的回答是:

你可能會需要一個系統中止,如果有很多的迭代沒有成功。

我會寫:

for i in range(numberofblocksyouwant):

while true: 
    numberofattempts = 0 
    create a block at a random x,y pos 
    if block collides with any existing blocks: 
     remove the block you just created 
     numberofattempts += 1 
     if numberofattempts > 1000: 
      return "took too many attempts" 
    else: 
     break