1
我试图创建一个风景,图像以不同的速度从屏幕的一侧移动到另一侧,创建视差效果。我使用一个名为BackgroundObject的Sprite类,但是当我尝试使用BackgroundObject创建一个Sprite时,我得到一个TypeError。Pygame在创建自定义精灵类时抛出“TypeError”
我正在使用的代码如下:
import pygame
from pygame.locals import *
import sys, random, os
import vector
# Background objects (for parallax)
class BackgroundObject(pygame.sprite.Sprite):
def _init_(self, x, y, image, speed):
pygame.sprite.Sprite._init_(self)
self.image = image
self.rect = self.image.get_rect()
self.rect.topleft = (x,y)
self.speed = speed
def update(self, time_passed):
moved_distance = time_passed * self.speed
self.rect.left += moved_distance
if self.rect.right < 0:
self.rect.left= self.rect.width
pygame.init()
screen = pygame.display.set_mode((768, 1024), 0, 32)
obstacleImage = "obstacle.png"
fenceImage = "fences.png"
cloudImage = "clouds.png"
cityImage = "cityscape.png"
groundImage = "bottom.png"
backgroundImage = "background.png"
pathName = "Assets"
# Sprites in the game
obstacles = pygame.sprite.Group()
backgrounds = pygame.sprite.OrderedUpdates()
backgroundOrder = []
backdrop = pygame.image.load(os.path.join(pathName + os.sep + backgroundImage))
fences = pygame.image.load(os.path.join(pathName + os.sep + fenceImage))
clouds = pygame.image.load(os.path.join(pathName + os.sep + fenceImage))
cityscape = pygame.image.load(os.path.join(pathName + os.sep + cityImage))
ground = pygame.image.load(os.path.join(pathName + os.sep + cityImage))
sprite = BackgroundObject(1280, 192, clouds, 192)
backgrounds.add(sprite)
backgrounds.add(BackgroundObject(0, 192, clouds, 192))
backgrounds.add(BackgroundObject(832, 768, cityscape, 154))
backgrounds.add(BackgroundObject(0, 768, cityscape, 154))
backgrounds.add(BackgroundObject(1728, 768, fences, 384))
backgrounds.add(BackgroundObject(0, 768, fences, 384))
backgrounds.add(BackgroundObject(992, 896, ground, 512))
backgrounds.add(BackgroundObject(0, 896, ground, 512))
titleScreen = pygame.image.load(os.path.join(pathName + backgroundImage))
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(titleScreen, titleScreen.rect)
backgrounds.update(time_passed)
backgrounds.draw()
for item in background:
if item.rect.right < 0:
item.rect.right += (item.rect.width * 2)
我recieving该错误消息如下,我不能弄明白它:
Traceback (most recent call last):
File "test.py", line 45, in <module>
sprite = BackgroundObject(1280, 192, clouds, 192)
File "/usr/lib/python2.7/dist-packages/pygame/sprite.py", line 114, in __init__
if groups: self.add(groups)
File "/usr/lib/python2.7/dist-packages/pygame/sprite.py", line 129, in add
else: self.add(*group)
File "/usr/lib/python2.7/dist-packages/pygame/sprite.py", line 129, in add
else: self.add(*group)
TypeError: add() argument after * must be a sequence, not int
这样做的窍门!这是我再也不会做的错误了。谢谢! –