[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[pygame] Re: Creating several instances of same image



Hi, this is my first mailing to the pygame list, AND my first mailing to any mailing list ever. So if something is messed up with this mail, please forgive me.

Nick Lunt wrote:

> Hi Folks,
>
> Im attempting to write a little space invaders type game.
>
> Im having problems working out how to get my aliens displayed onto the
> screen and then being able to manipulate them.
>
> I want the game to look like the original space invaders.
>
> Here's the relevant code:
>
>
>> class Alien(pygame.sprite.Sprite):
>> """ aliens only move as far left/right and the most left/right alien
>
>
> can move """
>
>> def __init__(self):
>> pygame.sprite.Sprite.__init__(self)
>> self.image, self.rect = loadImg('alien.png')
>
>
>
>> # Now create some Aliens()
>> alienDict = {}
>> for alien in range(1,13):
>> alienDict[alien] = Alien()
>
>
>
> Im thinking that Im doing this in completely the wrong way.
>
> Could anyone point me in the right direction to get 12 aliens on the screen
> (4 x 3).
>

1st: why a dictionary {} ? if you index by number, i'd use a list [].

also i'd always start indexing from 0 (range (12)), it's less confusing in the long way, you should get used to it.

i'd change the constructor (__init__) to use a position parameter
also i'd make it named (position = (default value)) so you can still use it without the parameter and it will use the default

class Alien(pygame.sprite.Sprite):
def __init__(self, position = (0,0)):
self.image, self.rect = loadImg('alien.png')
self.goto(position)

def goto (self, position):
# dunno if move is the right method
self.rect.move(position)

then i'd go as follows:

ROWS = 3
COLUMS = 4
LEFT = 100
TOP = 100

DISTANCE = 120

alienList = []

for z0 in range( COLUMNS ):
for z1 in range (ROWS ):
alien = Alien((LEFT + z0 * DISTANCE, TOP + z1 * DISTANCE))
alienList.append(alien)


so far, so good...

i hope it helps

yours, Jesterea