TypeError: pygame.sprite.Sprite.add()参数*后必须是可迭代的,而不是int



我的代码有一个问题,运行后,它说"pygame.sprite.Sprite.add()参数必须是一个可迭代对象,而不是"在行charS1=CharS(100,100,50,50)

我期待一个红色的矩形在我的窗口后,但我有这些问题

这里是我的代码,是的,几乎是从Youtube上复制的,但是它出错了

import pygame, os , sys , math 
from os import listdir
from os.path import isfile, join

pygame.init()
pygame.display.set_caption("Group 5: Female house from Ẻuope")
icon = pygame.image.load(join("img","good-icon.png"))
pygame.display.set_icon(icon)

WIDTH, HEIGHT = 1000, 600
FPS = 40
PLAYER_VEL = 3
window=pygame.display.set_mode((WIDTH, HEIGHT))

def get_background(name):
background = pygame.image.load(join("img",name))

return background

class CharS(pygame.sprite.Sprite):
COLOR = (255,0,0)
def __init__(self,x,y, width, heigth):
self.rect=pygame.Rect(x,y,width,heigth)
self.x_vel=0
self.y_vel=0
self.mask= None
self.direction= "right"
self.animation_count = 0
def move (self, dx, dy):
self.rect.x += dx
self.rect.y += dy
def move_right(self, vel):
self.x_vel = vel
if self.direction != "left":
self.direction = "left"
self.animation_count= 0
def loop(self, fps):
self.move( self.x_vel, self.y_vel)   

def draw(self, win):
pygame.draw.rect(win, self.COLOR, self.rect)
def draw(window, background,char):
window.blit(background, (0,0))
char.draw(window)
pygame.display.update()




def main(window):
clock = pygame.time.Clock()
background= get_background("backgrd.png")
charS1=CharS(100,100,50,50) #the problem went here
run= True
while run:  
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT: 
run = False
break
draw(window, background, charS1)    
pygame.quit()
quit()        



if __name__ == '__main__' :
main(window)   

我怎样才能解决这个问题?

您得到这个错误,因为基类pygame.sprite.Sprite没有初始化。您没有调用(super().__init__())的基类的构造函数。参见class super

class CharS(pygame.sprite.Sprite):
COLOR = (255,0,0)
def __init__(self,x,y, width, heigth):
super().__init__()                          # <---

self.rect=pygame.Rect(x,y,width,heigth)
# [...]

最新更新