[Tutor] Moveable and Animated Sprites
Jordan
wolfrage8765 at gmail.com
Mon Aug 15 04:09:27 CEST 2011
Is there a more Pythonic way to create the class
"MoveableAnimatedSheetSprite" I am using multiple inheritance but I see
that I am really loading the image twice when I call __init__ for
"AnimatedSheetSprite" and "MoveableSprite". Should I just make a
moveable class and have moveable items inherit it with out inheriting
from "Sprite"?
By the way the code does work as intended right now.
Thank you in advance, if you need more code or what ever just let me know.
import pygame
from vec2d import *
class Sprite(pygame.sprite.Sprite):
"""This defines a sprite that is a single image in a file that only
contains
it as an image."""
def __init__(self, imageName, startx=0, starty=0):
pygame.sprite.Sprite.__init__(self)
self.image=pygame.image.load(imageName)
self.rect=self.image.get_rect()
self.image.convert()
self.x=startx
self.y=starty
self.position=vec2d(self.x,self.y)
self.selected=False
def update(self):
pygame.sprite.Sprite.update(self)
class AnimatedSheetSprite(Sprite):
"""This defines a sprite that is multiple images but is in a image
file that
has only it's images."""
def __init__(self, imageName, startx=0, starty=0, height=0, width=0):
Sprite.__init__(self, imageName, startx, starty)
self.images=[]
masterWidth, masterHeight=self.image.get_size()
for i in xrange(int(masterWidth/width)):
self.images.append(self.image.subsurface((i*width,0,width,height)))
self.image=self.images[0]
self.maxFrame=len(self.images)-1
self.frame=0
def animate(self):
if self.frame < self.maxFrame:
self.frame=self.frame+1
else:
self.frame=0
self.image=self.images[self.frame]
def update(self):
Sprite.update(self)
self.animate()
class MoveableSprite(Sprite):
"""This defines a sprite that is a single image in a file that only
contains
it as an image. But this sprite can move."""
def __init__(self, imageName, startx=0, starty=0, targetx=0,
targety=0, speed=2):
Sprite.__init__(self, imageName, startx, starty)
self.target=vec2d(targetx,targety)
self.speed=speed
def move(self):
self.direction=self.target-self.position
if self.direction.length > self.speed:
self.position= self.position+self.speed
def update(self):
Sprite.update(self)
self.move()
class MoveableAnimatedSheetSprite(MoveableSprite, AnimatedSheetSprite):
"""This defines a sprite that is multiple images but is in a image
file that
has only it's images. But this sprite can move."""
def __init__(self, imageName, startx=0, starty=0,targetx=0,
targety=0, speed=2,
height=0, width=0):
MoveableSprite.__init__(self, imageName, startx, starty,
targetx, targety, speed)
AnimatedSheetSprite.__init__(self, imageName, startx, starty,
height, width)
def update(self):
MoveableSprite.update(self)
AnimatedSheetSprite.update(self)
--
Jordan Farrell
More information about the Tutor
mailing list