I am trying to make a simple version of space invaders, I keep running into the same error
ValueError: list.remove(x): x not in list
trying to remove the invaders once they've been hit.
Here is the code.
def killEnemies(bullets, enemies):
for bullet in bullets:
for x in enemies:
for y in x:
if bullet.top <= y.bottom and bullet.top >= y.top:
if bullet.left >= y.left and bullet.right <= y.right:
x.remove(y)
bullets.remove(bullet)
The problem only occurs when the if statements are True, and the console says that the error occurs in the last line
Here is the rest of the code
import pygame, sys
from pygame.locals import *
pygame.init()
FPS = 30
fpsClock = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((800, 660), 0, 32)
pygame.display.set_caption('Space Invaders')
white = (255, 255, 255)
black = (0, 0, 0)
shipx = 50
shipy = 630
DISPLAYSURF.fill(black)
timer = fpsClock.tick()
time = 0
direction = ''
bullets = []
bulletx = shipx + 25
bullety = shipy - 50
enemies = [[], [], [], [], [], [], []]
shields = []
def drawEnemies(enemies):
y = 0
for n in enemies:
x = 0
for f in range(7):
enemy = pygame.draw.rect(DISPLAYSURF, white, (30 + x, 40 + y, 75, 20))
n.append(enemy)
x += 110
y += 30
return enemies
def killEnemies(bullets, enemies):
for bullet in bullets:
for x in enemies:
for y in x:
if bullet.top <= y.bottom and bullet.top >= y.top:
if bullet.left >= y.left and bullet.right <= y.right:
x.remove(y)
bullets.remove(bullet)
def moveBullets(bullets):
for bullet in bullets:
bullet.top -= 15
for b in bullets:
pygame.draw.rect(DISPLAYSURF, white, b)
while True:
if direction == 'left':
shipx -= 8
bulletx -= 8
elif direction == 'right':
shipx += 8
bulletx += 8
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
key = pygame.key.get_pressed()
if key[K_LEFT]:
direction = 'left'
elif key[K_RIGHT]:
direction = 'right'
elif key[K_SPACE]:
bullet = pygame.draw.line(DISPLAYSURF, white, (bulletx, bullety), (bulletx, bullety - 25), 2)
bullets.append(bullet)
if event.type == KEYUP:
direction = ''
time += timer
DISPLAYSURF.fill(black)
pygame.draw.polygon(DISPLAYSURF, white, ((shipx, shipy), (shipx + 25, shipy - 50), (shipx + 50, shipy)), 1)
drawEnemies(enemies)
moveBullets(bullets)
killEnemies(bullets, enemies)
pygame.display.update()
fpsClock.tick(FPS)