我对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: ValueError: 0x000002D6982A5F28>的对象不在列表中
下面是完整的错误消息: pygame 1.9.6,来自pygame社区的Hello。<main.projectile跟踪(最近一次调用):文件“E:\Python\Script\Projects\Login System\spaceInvaders.py",第317行,在main()文件”E:\Python\Script\Projects\Login System\spaceInvaders.py“中,第298行,在main hitbaricade()文件”E:\Python\Script\Projects\Login System\spaceInvaders.py“中,第250行,在hitbaricade bullets.pop(bullets.index(项目))中,#这一条打断了ValueError: 0x0000012B51DFE2E8>上的System\spaceInvaders.py对象不在列表中
发布于 2019-07-24 05:32:30
原因是你一次又一次地弹出同一个项目。你应该把它从内环移开。
在迭代列表时,您应该避免修改它。
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]https://stackoverflow.com/questions/57175731
复制相似问题