尝试生成 n 个不碰撞的精灵; pygame 崩溃

问题描述 投票:0回答:1

我对 PyGame 很陌生(两天前开始学习),我正在尝试制作一个游戏,在我的岛上生长随机数量的浆果。

我的(理想)算法会

  1. 在静态浆果丛中生成
  2. 检查它是否与我之前生成的任何浆果发生碰撞
  3. 如果发生碰撞,请将其删除并生成另一个不发生碰撞的

我为 genBerries 函数编写了以下代码:

def genBerries(xRange, yRange, bushCount):  
    sucSpawns = 0
    berries = []
    while sucSpawns < bushCount:  # while you've spawned less than you want to
        spawnX = random.randint(xRange[0], xRange[1])  # randomise x coordinate for berry bush
        spawnY = random.randint(yRange[0], yRange[1])  # randomise y coordinate for berry bush
        berry = Berry(10, 5, 3, spawnX, spawnY)  # make a berry at this x and y
        for j in berries:
            collide = berry.rect.colliderect(j)  # check if berry colliding with some other berry
            if collide:
                berry.kill()  # if it is, get rid of it (and while loop will let u try again)
            else:
                sucSpawns += 1
                berries.append(berry)  # add this berry to the list of berries you've spawned successfully

xRange = island.rect.left, island.rect.right - 96  # defining x range berries can spawn in
yRange = (island.rect.top + 96, island.rect.bottom)  # defining y range berries can spawn in
bushCount = math.floor(random.normalvariate(conf['bA'], conf['bA']/5))  # defining how many berries spawn

genBerries(xRange, yRange, bushCount)

但是,一旦我这样做...

某种堆栈溢出(哈哈)似乎意味着这个进程没有终止?然后黑屏??

如果我注释掉碰撞部分,它会给我(根据需要,但重叠):

python pygame collision-detection
1个回答
0
投票

当您识别出碰撞时,您必须离开循环,并且只能将该对象插入到列表中一次,但不是针对每个不发生碰撞的对象:

while len(berries) < bushCount:
    spawnX = random.randint(xRange[0], xRange[1]) 
    spawnY = random.randint(yRange[0], yRange[1])
    berry = Berry(10, 5, 3, spawnX, spawnY)
    collide = None 
    for j in berries:
        collide = berry.rect.colliderect(j)
        if collide:
            break
            berry.kill()
    if collide = None:
        berries.append(berry)  
© www.soinside.com 2019 - 2024. All rights reserved.