简体   繁体   English

这种类型错误的解决方案是什么:列表索引必须是整数或切片,而不是 str?

[英]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:尝试退出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.因为move是一个只有一个元素的列表。 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 move一个字典,而不是一个包含一个字典元素的列表
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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类型错误:列表索引必须是整数或切片,而不是 str - Type Error: list indices must be integers or slices, not str 错误列表索引必须是整数或切片,而不是str - error list indices must be integers or slices, not str 列表索引必须是整数或切片,而不是 str 错误 Python - list indices must be integers or slices, not str error Python 我不断收到此错误:列表索引必须是整数或切片,而不是 str - I keep getting this error: list indices must be integers or slices, not str Goodreads API错误:列表索引必须是整数或切片,而不是str - Goodreads API Error: List Indices must be integers or slices, not str Python 错误:列表索引必须是整数或切片,而不是 str - Python Error : list indices must be integers or slices, not str 循环时出现错误“列表索引必须是整数或切片,而不是 str” - Error "list indices must be integers or slices, not str" while looping TypeError:列表索引必须是整数或切片,而不是str <encoding error> - TypeError: list indices must be integers or slices, not str <encoding error> python json 列表索引必须是整数或切片,而不是 str 错误 - python json list indices must be integers or slices, not str error 在数组中,列表索引必须是整数或切片,而不是 str 错误 python - In an array, list indices must be integers or slices, not str error python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM