Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Space Invaders
#1
Hello, I'm new in the forum and my native language isn't English so I'm sorry if I do some mistakes. I need to do a homework (Space Invaders) and I don't know why but I keep getting this error : IndexError: Cannot choose from an empty sequence. Can anyone help me? Here is my code :
import pygame,sys
from pygame.locals import *
import random

pygame.init()
pygame.font.init()
mainclock= pygame.time.Clock()
window=pygame.display.set_mode((450,560,),0,32)     	# Taille fenêtre du jeu
pygame.display.set_caption('SpaceInvader')          	# titre de la fenêtre
xs=20							# coordonnées de départ du vaisseau
ys=500
i=0
missile=[]
Gauche=False
Droite=False
Feu = False
Texty = pygame.font.Font('SUPERPOI_R.TTF', 10)
Obj_texte = Texty.render('les envahisseurs', 0, (0,0,255))
clock = pygame.time.Clock()
Movespeed=4
toile=pygame.image.load('toile.png')
background=pygame.image.load('background.png')
ship1=pygame.image.load('ship1.png')
ship2=pygame.image.load('ship2.png')

m=[]
meteor=pygame.image.load('meteor.png')
temptir1 =  i + random.randint(30,80)
i=0
for b in range (450,560,10):
    for o in range (20,300,50):
       	choix1=random.choice(m)
        m.append(pygame.Rect(choix.bottom+0,choix.bottom,0,0))

cible=[]
invader1=pygame.image.load("invader1.png")
invader2=pygame.image.load("invader2.png")
i=0
for n in range(200,400,100):
    for i in  range(20,300,50):
        cible.append(pygame.Rect(i,n,32,24))    # Liste des rectangles des images cibles

tir_cible=[]
temptir =  i + random.randint(15,60)
def ajouter_temptir():
       	choix=random.choice(cible)
        tir_cible.append(pygame.Rect(choix.left+12,choix.bottom,6,16))

while True:
    window.blit(background,(0,0))	    # Image arrière plan
    window.blit(Obj_texte,(50,20))			# Placer le texte

    for alien in cible:                         #deplacement des aliens
        alien.left+=Movespeed
    for alien in cible:
        if alien.right>450 or alien.left<0:      #deplacement sur le cote
            Movespeed*=-1
            break

    if temptir <= i:
	       temptir =  i + random.randint(15,60) #Tir des aliens
	       ajouter_temptir()

    if temptir1 <= i:
	       temptir1 =  i + random.randint(30,80) #Asteroïdes
	       ajouter_temptir1()

    for event in pygame.event.get():			# Traiter les évènements du clavier
        if event.type== KEYDOWN:
            if event.key==K_ESCAPE:
               pygame.quit()
               sys.exit()
            if event.key==K_RIGHT:
                Droite = True
            if event.key==K_LEFT:
                Gauche = True

        if event.type== KEYUP:
            if event.key==K_RIGHT:
                Droite = False
            if event.key==K_LEFT:
                Gauche = False
            if event.key==K_SPACE:
                missile.append(pygame.Rect(xs+8,ys,6,16))

    i=i+1
    if Gauche and xs>10: xs =xs-10
    if Droite and xs <400 : xs +=10

    for tir in missile:					# pour chaque missile existant
        tir.top=tir.top-20				# soustraire 10 à la coordonnée du point haut
        window.blit(toile,tir)		# toile d'arraignée
        if tir.top==100:				# si le missile arrive en haut de l'écran
            missile.remove(tir)				# supprimer le missile de la liste
        for c in cible:
            if tir.colliderect(c):
                missile.remove(tir)
                cible.remove(c)

    for tir in tir_cible:
        tir.top=tir.bottom+20
        window.blit(toile,tir)
        if tir.bottom==-20:
            tir_cible.remove(tir)

    for tir2 in m:
        tir2.top=tir.bottom+20
        window.blit(meteor,tir)
        if tir2.bottom==-20:
            m.remove(tir)


    if int(i/20)%2 ==1:
     window.blit(ship1,(xs,ys))
    else:
     window.blit(ship2,(xs,ys))

    for c in cible:
        if int(i/20)%2 ==1:
            window.blit(invader1,c)
        else:
            window.blit(invader2,c)


    pygame.display.update()
    clock.tick(30)
PS : Some codes are in french like gauche which means left. Thanks in advance.
Reply
#2
You should make sure to post the entire error, exactly as it appears, because it gives useful information about the error (like on which line it occurred).

At a guess, though, on line 32, what do you expect the value of choix1 to be on the first iteration of that loop, given that m is an empty list (from line 26)? What do you want to happen in that case?
Reply
#3
(Dec-31-2019, 05:09 PM)ndc85430 Wrote: You should make sure to post the entire error, exactly as it appears, because it gives useful information about the error (like on which line it occurred).

At a guess, though, on line 32, what do you expect the value of choix1 to be on the first iteration of that loop, given that m is an empty list (from line 26)? What do you want to happen in that case?

Hello, thank you for your reply and I'm sorry for my late. When I click to "copy" it gives me this :
Message Nom de Fichier (it means File Name) Ligne (Line) Position
Traceback
<module> C:\Cours\ISN\EduPython\Space Invaders.py 33
choice C:\EduPython\App\lib\random.py 255
IndexError: Cannot choose from an empty sequence

Here is a screenshot of my error :
[Image: k20BmCVG]

In line 26 I'm loading images (meteors more precisely) to make them appear and fall down in my game. The line 32 is to make them appear randomly (to make "m" appear randomly). That's what I'm trying to do. It was working 2 weeks ago. It was not correctly working there was a kind of glitch and I was trying to fix it but I think that I added something and I don't remember what was the code :/

I can't edit my message anymore so I'm writing a reply sorry for that. I moved the line 33 and put it back to it's place and then suddenly this error appeared Syntax Error : unindent does not match any outer indentation level.
ScreenShot : [Image: 4mKWLvpG]
Reply
#4
(Jan-01-2020, 09:10 PM)MelihsahCelik Wrote: In line 26 I'm loading images

no, your line 26 is you making an empty list.
m=[]
and then on line 32...
choix1=random.choice(m)
You are taking a random choice from that empty list.

That's why you get the error
Error:
IndexError: Cannot choose from an empty sequence
The empty sequence is "m=[]".
Reply
#5
(Jan-01-2020, 11:18 PM)michael1789 Wrote:
(Jan-01-2020, 09:10 PM)MelihsahCelik Wrote: In line 26 I'm loading images

no, your line 26 is you making an empty list.
m=[]
and then on line 32...
choix1=random.choice(m)
You are taking a random choice from that empty list.

That's why you get the error
Error:
IndexError: Cannot choose from an empty sequence
The empty sequence is "m=[]".

Thanks for your reply and your help I tried to change and add some codes to see if it works but it still don't work. I'm new to Python so I don't really know what to do now :/ (I'm only doing 2 hours per week in school and sometimes at home).
Reply
#6
(Jan-02-2020, 08:03 PM)MelihsahCelik Wrote:
(Jan-01-2020, 11:18 PM)michael1789 Wrote: no, your line 26 is you making an empty list.
m=[]
and then on line 32...
choix1=random.choice(m)
You are taking a random choice from that empty list.

That's why you get the error
Error:
IndexError: Cannot choose from an empty sequence
The empty sequence is "m=[]".

Thanks for your reply and your help I tried to change and add some codes to see if it works but it still don't work. I'm new to Python so I don't really know what to do now :/ (I'm only doing 2 hours per week in school and sometimes at home).

It works I changed my code and it is working now :) Thanks for your help. If anyone needs my new code is this :
import pygame,sys
from pygame.locals import *
import random

pygame.init()
pygame.font.init()
mainclock= pygame.time.Clock()
window=pygame.display.set_mode((450,560,),0,32)     	# Taille fenêtre du jeu
pygame.display.set_caption('SpaceInvader')          	# titre de la fenêtre
xs=20							# coordonnées de départ du vaisseau
ys=500
i=0
missile=[]
Gauche=False
Droite=False
Feu = False
Texty = pygame.font.Font('SUPERPOI_R.TTF', 10)
Obj_texte = Texty.render('les envahisseurs', 0, (0,0,255))
clock = pygame.time.Clock()
Movespeed=4
toile=pygame.image.load('toile.png')
background=pygame.image.load('background.png')
ship1=pygame.image.load('ship1.png')
ship2=pygame.image.load('ship2.png')
meteor=pygame.image.load('meteor.png')

cible=[]
invader1=pygame.image.load("invader1.png")
invader2=pygame.image.load("invader2.png")
i=0
for n in range(200,400,100):
    for i in  range(20,300,50):
        cible.append(pygame.Rect(i,n,32,24))    # Liste des rectangles des images cibles

tir_cible=[]
temptir =  i + random.randint(15,60)
def ajouter_temptir():
       	choix=random.choice(cible)
        tir_cible.append(pygame.Rect(choix.left+12,choix.bottom,6,16))

tir_meteor=[]
temptir1 =  i + random.randint(15,60)
def ajouter_temptir1():
       	choix1=random.choice(cible)
        tir_meteor.append(pygame.Rect(choix1.left+12,choix1.bottom,6,16))

while True:
    window.blit(background,(0,0))	    # Image arrière plan
    window.blit(Obj_texte,(50,20))			# Placer le texte

    for alien in cible:                         #deplacement des aliens
        alien.left+=Movespeed
    for alien in cible:
        if alien.right>450 or alien.left<0:      #deplacement sur le cote
            Movespeed*=-1
            break

    if temptir <= i:
	       temptir =  i + random.randint(15,60) #Tir des aliens
	       ajouter_temptir()

    if temptir1 <= i:
	       temptir1 =  i + random.randint(15,60) #Tir des aliens
	       ajouter_temptir1()

    for event in pygame.event.get():			# Traiter les évènements du clavier
        if event.type== KEYDOWN:
            if event.key==K_ESCAPE:
               pygame.quit()
               sys.exit()
            if event.key==K_RIGHT:
                Droite = True
            if event.key==K_LEFT:
                Gauche = True

        if event.type== KEYUP:
            if event.key==K_RIGHT:
                Droite = False
            if event.key==K_LEFT:
                Gauche = False
            if event.key==K_SPACE:
                missile.append(pygame.Rect(xs+8,ys,6,16))

    i=i+1
    if Gauche and xs>10: xs =xs-10
    if Droite and xs <400 : xs +=10

    for tir in missile:					# pour chaque missile existant
        tir.top=tir.top-20				# soustraire 10 à la coordonnée du point haut
        window.blit(toile,tir)		# toile d'arraignée
        if tir.top==100:				# si le missile arrive en haut de l'écran
            missile.remove(tir)				# supprimer le missile de la liste
        for c in cible:
            if tir.colliderect(c):
                missile.remove(tir)
                cible.remove(c)

    for tir in tir_cible:
        tir.top=tir.bottom+20
        window.blit(toile,tir)
        if tir.bottom==-20:
            tir_cible.remove(tir)

    for m in tir_meteor:
        m.top=m.bottom+20
        window.blit(meteor,m)
        if m.bottom==-20:
            tir_meteor.remove(m)


    if int(i/20)%2 ==1:
     window.blit(ship1,(xs,ys))
    else:
     window.blit(ship2,(xs,ys))

    for c in cible:
        if int(i/20)%2 ==1:
            window.blit(invader1,c)
        else:
            window.blit(invader2,c)


    pygame.display.update()
    clock.tick(30)
Instead of using the empty "m" sequence I created another one "tir_meteor". Smile
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020