2
votes

Quelle est la solution à cette erreur de type: les index de liste doivent être des entiers ou des tranches, pas str?

Je suis un débutant alors pardon si je n'ai pas posé les questions selon la norme

IL Y A QUELQUES JOURS, j'ai créé un programme mais il montre l'erreur suivante, j'ai fait quelques recherches mais aucune des réponses ne correspondait à ce type de question, l'erreur est la suivante:

win_w  =640
win_h  =640
cell_s =20
cellWidth=int(win_w/cell_s)-1
cellHeight=int(win_h/cell_s)-1

et mon code était:

startX=random.randint(20,cellWidth)
startY=random.randint(20,cellHeight)
snakeCoords=[{"x":startX,"y":startY},
             {"x":startX-1,"y":startY},
             {"x":startX-2,"y":startY}]

dans apple, le code va comme ceci:

apple=randomlocation()
def randomlocation():
           return {"x":random.randint(20,cellWidth),
                   "y":random.randint(20,cellHeight)}

dans snakecoords, le code va comme ceci:

def run2(score,run):
  global appleX,appleY,snakeCoords
  startX=random.randint(20,cellWidth)
  startY=random.randint(20,cellHeight)
  apple=randomlocation()
  appleX=apple['x']*cell_s
  appleY=apple['y']*cell_s
  snakeCoords=[{"x":startX,"y":startY},
               {"x":startX-1,"y":startY},
               {"x":startX-2,"y":startY}]
  direction=RIGHT
  assert win_w % cell_s==0
  assert win_h % cell_s==0
  
  
  while run:
     
     if snakeCoords[head]['x']==19 or snakeCoords[head]['y']==19:
            gameover(window)
            pygame.time.wait(500)
            run=False
            terminate()
            sys.exit()
     if snakeCoords[head]['x']==win_w-20 or snakeCoords[head]['y']==win_h-20:
            gameover(window)
            pygame.time.wait(500)
            run=False                 
            terminate()
            sys.exit()
   
     for body in snakeCoords[1:]:
         if snakeCoords[head]['x']==body['x'] and snakeCoords[head]['y']==body['y']:
             gameover(window)
             pygame.time.wait(500)
             terminate()
             sys.exit()
             
 
     if direction==UP:
          move={'x':snakeCoords[head]['x']-1,'y':snakeCoords[head]['y']}
     if direction==DOWN:
          move={'x':snakeCoords[head]['x']+1,'y':snakeCoords[head]['y']}
     if direction==RIGHT:
          move={'x':snakeCoords[head]['x'],'y':snakeCoords[head]['y']+1}
     if direction==LEFT:
          move={'x':snakeCoords[head]['x'],'y':snakeCoords[head]['y']-1}
     snakeCoords.insert(0,move)
     
     
   
     if apple['x']==snakeCoords[head]['x'] and apple['y']==snakeCoords[head]['y']:
            apple=randomlocation()
            drawgame.drawapple(red)
            score+=1
            if appleX==snakeCoords[head]['x'] and direction==RIGHT:
                newhead=[{'x':startX-3,'y':startY}]
                snakeCoords+=newhead
            if appleX==snakeCoords[head]['x'] and direction==LEFT:
                newhead=[{'x':startX+3,'y':startY}]
                snakeCoords+=newhead
            if appleY==snakeCoords[head]['y'] and direction==UP:
                newhead=[{'x':startX,'y':startY+3}]
                snakeCoords+=newhead
            if appleY==snakeCoords[head]['y'] and direction==DOWN:
                newhead=[{'x':startX,'y':startY-3}]
                snakeCoords+=newhead
            pygame.display.update()
                        

     if score==10:
            gameover(window)
            pygame.time.wait(500)
            
            
   
     for event in pygame.event.get():
        if event.type==pygame.QUIT:
           run=False
           terminate()
           sys.exit()
           
           
        
        if event.type==KEYDOWN:
             if event.key==K_RIGHT and direction!=LEFT:
                direction=RIGHT
             elif event.key==K_LEFT  and direction!=RIGHT:
                direction=LEFT
             elif event.key==K_UP and direction!=DOWN:
                direction=UP
             elif event.key==K_DOWN  and direction!=UP:
                direction=DOWN
             elif event.key==K_ESCAPE :
                terminate()
                sys.exit()
             else:
                print("Invalid Key Pressed")
                
    
if __name__=="__main__":
    main(run)

et la largeur et la hauteur de la cellule sont:

if apple["x"]==snakeCoords[head]["x"] and apple["y"]==snakeCoords[head]["y"]:

TypeError: list indices must be integers or slices, not str

Guidez-moi s'il-vous-plaît.


2 commentaires

Le code de la question ne vide jamais les opérations de dessin dans la fenêtre (généralement effectuées par pygame.display.update() ou pygame.display.flip() ). Cependant, la question n'inclut pas le code de la fonction run() , veuillez inclure cette fonction.


@ Rabbid76, l'erreur se produisait dans la section mon code donnée dans la question.


3 Réponses :


2
votes

Je suggère de le coder comme

run = True
while run :
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            run = False


1 commentaires

Monsieur ça n'a pas marché



0
votes

Essayez de quitter pygame:

while True:
 for event in pygame.event.get():
    if event.type==pygame.QUIT:
        pygame.quit()
        sys.exit()


1 commentaires

Monsieur, je l'ai déjà fait.



0
votes

Le problème est causé par la ligne:

if direction == UP:
    move = {'x':snakeCoords[head]['x']-1,'y':snakeCoords[head]['y']}
if direction == DOWN:
    move = {'x':snakeCoords[head]['x']+1,'y':snakeCoords[head]['y']}
if direction == RIGHT:
    move = {'x':snakeCoords[head]['x'],'y':snakeCoords[head]['y']+1}
if direction == LEFT:
    move = {'x':snakeCoords[head]['x'],'y':snakeCoords[head]['y']-1}
snakeCoords.insert(0, move)

car move est une liste avec un élément. L'élément est un dictionnaire

snakeCoords.insert(0, *move)

Il existe 2 possibilités pour résoudre le problème:

  1. Utilisez l' opérateur astérisque (*) pour décompresser les listes:

snakeCoords.insert(0, move)

move=[{'x':snakeCoords[head]['x'],'y':snakeCoords[head]['y']-1}]
  1. Faire move un dictionnaire, plutôt qu'une liste avec un élément qui est un dictionnaire
snakeCoords.insert(0,move)


0 commentaires