我对python很陌生,我试图使用pygame制作一个简单的太空侵略者游戏,但是每当尝试弹出列表中的项目符号之一时,我都会不断收到此错误。我已经能够通过其他碰撞弹出子弹,但无法使它起作用。
def hitbaricade():
global bullets, barricades, enemybullets
for bullet in bullets:
for barricade in barricades:
if abs(barricade.x + (barricade.width//2) - bullet.x) < barricade.width//2 + 2 and abs(barricade.y + barricade.height//2 - bullet.y) < barricade.height//2 + 2:
bullets.pop(bullets.index(bullet)) #this one breaks
barricades.pop(barricades.index(barricade)) #this one works
for ebullet in enemybullets:
for barricade in barricades:
if abs(barricade.x + (barricade.width//2) - ebullet.x) < barricade.width//2 + 5 and abs(barricade.y + barricade.height - ebullet.y) < defender.height:
enemybullets.pop(enemybullets.index(ebullet)) #this one breaks
barricades.pop(barricades.index(barricade)) #this one works
在此处在此处设置项目符号列表的位置,列表在此之前被声明为空列表
if keys[pygame.K_SPACE] and bulletDelay > 10 and len(bullets) < 1:
bullets.append(projectile(defender.x + (defender.width//2), 460, -1, 10))
bulletDelay = 0
在这里我设置路障列表,该列表也早先被视为空列表
def baricadeSetup():
global barricades
x = 45
y = 410
x2 = x
width = 5
height = 5
loop = 0
for i in range(0,4):
for i in range(0,30):
barricades.append(shield(x,y,width,height))
loop += 1
x += 5
if loop >= 10:
loop = 0
x = x2
y += 5
x2 += 125
x = x2
y = 410
loop = 0
我试图获取输出,其中列表中的项目会弹出,但我会收到错误:ValueError:主要。位于0x000002D6982A5F28>的投射对象不在列表中
这是完整的错误消息: pygame 1.9.6 pygame社区您好。 https://www.pygame.org/contribute.html 追溯(最近一次通话): 文件“ E:\ Python \ Scripts \ Projects \ Login System \ spaceInvaders.py”,第317行,在 主要() 主文件“ E:\ Python \ Scripts \ Projects \ Login System \ spaceInvaders.py”,第298行 hitbaricade() 文件“ E:\ Python \ Scripts \ Projects \ Login System \ spaceInvaders.py”,行250,位于Hitbaricade中 bullets.pop(bullets.index(bullet))#这打破了 ValueError:<< strong>主要。位于0x0000012B51DFE2E8>的弹丸对象不在列表中
答案 0 :(得分:0)
原因是您一次又一次弹出同一项目。您应该将其从内部循环中移出。
并且您应该避免在迭代列表时对其进行修改。
def hitbaricade():
global bullets, barricades, enemybullets
bullets_removed = set()
barricades_removed = set()
for bullet in bullets:
for barricade in barricades:
if abs(barricade.x + (barricade.width//2) - bullet.x) < barricade.width//2 + 2 and abs(barricade.y + barricade.height//2 - bullet.y) < barricade.height//2 + 2:
bullets_removed.add(bullet)
barricades_removed.add(barricade)
bullets = [bullet for bullet in bullets if bullet not in bullets_removed]
barricades = [barricade for barricade in barricades if barricade not in barricades_removed]
ebullets_removed = set()
barricades_removed = set()
for ebullet in enemybullets:
for barricade in barricades:
if abs(barricade.x + (barricade.width//2) - ebullet.x) < barricade.width//2 + 5 and abs(barricade.y + barricade.height - ebullet.y) < defender.height:
ebullets_removed(ebullet)
barricades_removed(barricade)
enemybullets = [ebullet for ebullet in enemybullets if ebullet not in ebullets_removed]
barricades = [barricade for barricade in barricades if barricade not in barricades_removed]