2016-11-26 40 views
-2

我通過pygame編碼2048遊戲。以下是我的代碼的相關部分:分配給列表時對象不可迭代

class Data(): 
    def __init__(self): 
      self.data = getnull() 
      self.score = 0 
    def updatesprites(self):   # EXP 
      spritelist = [[],[],[],[]] 
      for count in range(4): # for row loop 
       for i in range(4): # per column loop 
        if self.data[count][i] != 0: 
         spritelist[count]+= newSprite(str(self.data[count] [i])+".png") # error occurs here 
         spritelist[count][i].move(15 + i*115, 15 + count*115) 
         showSprite(spritelist[count][i]) 
class newSprite(pygame.sprite.Sprite): 
    def __init__(self,filename): 
     pygame.sprite.Sprite.__init__(self) 
     self.images=[] 
     self.images.append(loadImage(filename)) 
     self.image = pygame.Surface.copy(self.images[0]) 
     self.currentImage = 0 
     self.rect=self.image.get_rect() 
     self.rect.topleft=(0,0) 
     self.mask = pygame.mask.from_surface(self.image) 
     self.angle = 0 

    def addImage(self, filename): 
     self.images.append(loadImage(filename)) 

    def move(self,xpos,ypos,centre=False): 
     if centre: 
      self.rect.center = [xpos,ypos] 
     else: 
      self.rect.topleft = [xpos,ypos] 

---------------- Main ----------------- -

from functions import * 
from config import * 
from pygame_functions import * 
import pygame 
screenSize(475,475) # call screen init 
gameboard = newSprite("game board.png") # createboard 
showSprite(gameboard) 
game = Data() 
game.updatesprites() 

while True: 
    pass 

時game.updatesprites()被調用時, 「newSprite對象不是可迭代」 的錯誤在功能Data.updatesprites提出

+3

請考慮尋找PEP008(python風格指南) – CodenameLambda

+0

總是添加完整的錯誤消息(Traceback)。我們不能運行代碼並看到它,但有許多有用的信息 - 即。哪一行出問題。 – furas

回答

0

+符連接列表和字符串,並增加了數字。

你想要做的是將一個元素添加到列表中。

這是做如下:

li.append(element) # adds the element to the end of the list 

或者你的情況:

spritelist[count].append(newSprite(str(self.data[count][i]) + ".png")) 

另一種解決辦法:你可以創建一個新的類型,可以讓你添加元素,你試圖方式:

class UglyList(list): 
    def __iadd__(self, other): 
     self.append(other) 

你需要改變這裏另一條線路:

spritelist = [UglyList() for i in range(4)]