PyGame模块学习:Sprite

Plux posted @ 2008年1月30日 18:48 with tags pygame python , 2815 阅读

发现PyGame文档中的中文资料甚少,学习PyGame真的有点困难,但是Python又是如此容易学习的语言,不肯放弃。

我想许多人会对pygame.sprite.Sprite类不理解,至少我是这样,我看过一些程序后也还是觉得有点抽象──它到底如何绘制的呢?(绘制pygame.sprite.Sprite类里的哪个东西?)

用dir(pygame.sprite.Sprite)出来的东西如下:

['__class__','__delattr__','__dict__','__doc__','__getattribute__','__hash__','__init__','__module__',
'__new__','++reduce__','__reduce_ex__','__repr__','__setattr__','__str__','__weakref__','add',
'add_internal','alive','groups','kill','remove','remove_internal','update']

看不到有什么属性需要覆盖,就只有update方法,但这个方法里我到底该填些什么呢?任意Surface?那么它又怎么把我想画的画出来呢?

然后pygame.sprite.Sprite.__doc__返回如下:

The base class for your visible game objects.
       The sprite class is meant to be used as a base class
       for the objects in your game. It just provides functions
       to maintain itself in different groups.

       You can initialize a sprite by passing it a group or sequence
       of groups to be contained in.

       When you subclass Sprite, you must call this
       pygame.sprite.Sprite.__init__(self) before you add the sprite
       to any groups, or you will get an error.

好像没什么用……

其实,自己的猜想是最重要的,然后是论证自己的猜想(怎么好像那么复杂,呵呵,不是名家的话是这样的啦)我试着继承pygame.sprite.Sprite类,胡乱的写些东西下去,再根据网上一些例程

调用:

a = A() # A继承于pygame.sprite.Sprite类
allsprites = pygame.sprite.RenderPlain((a))

初始化。

在循环中调用

allsprites.update()
allsprites.draw(screen) #screen就是pygame.display.set_mode()返回的屏幕

出现了意想不到的效果,错误如下:

'A' object has no attribute 'image'
'A' object has no attribute 'rect'

为什么会这样?原来allsprite.draw()那个方法里就是绘制继承于pygame.sprite.Sprite类的image图像,rect属性保存的就是位置大小等信息。(动画就在update方法里实现)

现在,知道pygame.sprite.Sprite里重写些什么了吧。

Enjoy PyGame!
 

 


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter