我对 PyGame 很陌生(两天前开始学习),我正在尝试制作一个游戏,在我的岛上生长随机数量的浆果。
我的(理想)算法会
我为 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)
但是,一旦我这样做...
某种堆栈溢出(哈哈)似乎意味着这个进程没有终止?然后黑屏??
当您识别出碰撞时,您必须离开循环,并且只能将该对象插入到列表中一次,但不是针对每个不发生碰撞的对象:
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)