简体   繁体   中英

What is the solution to this type error :list indices must be integers or slices, not str?

I am a beginner so pardon if I haven't asked the questions according to the standard

FEW DAYS AGO, I have created a program but it shows the following error, I did some research but none of the answers were not of this type of question, the error is as follows:

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

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

and my code was:

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)

in apple the code goes like this:

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

in snakecoords the code goes like this:

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}]

and cell width and height are:

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

Please guide me.

I suggest coding it like

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

Try exit pygame:

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

The issue is caused by the line:

 snakeCoords.insert(0,move)

because move is a list with one element. The element is a dictionary

move=[{'x':snakeCoords[head]['x'],'y':snakeCoords[head]['y']-1}]

There are 2 possibilities to solve the issue:

  1. Use the asterisk(*) operator to unpacking the Lists:

snakeCoords.insert(0, move)

snakeCoords.insert(0, *move)
  1. Make move a dictionary, rather than a list with one element that is a dictionary
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM