我正在通过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]
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()时,函数Data.updatesprites中出现“newSprite对象不可迭代”错误
答案 0 :(得分: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)]