STEP ONE: ADDING A MOVE FUNCTION TO OUR CLASS
Inside our class declaration we need to define a new function called move
def move(self):
and inside that function we need to modify the x and/or y values of the class.
- Move Down: increase the y value
self.y += 1 - Move Up: decrease the y value
self.y -= 1 - Move Right: increase the x value
self.x += 1 - Move Left: decrease the x value
self.x -= 1
def move(self):
self.y += 1
STEP TWO: Calling the class.move() function from inside the game loop
Find where you have called the class.draw() function and now call the class.move() function before you draw in.
for dog in dogArray:
dog.move()
dog.draw()
STEP THREE: Removing an instance from a class array
We will remove an instance of the class once it has got to the bottom of the screen.
Inside the class.move() function we need to check if the instance has got to the bottom of the screen and if so, remove it.
if self.y > display_height – 50:
dogArray.remove(self)
def move(self):
self.y += 1
if self.y > display_height - 50:
dogArray.remove(self)
STEP FOUR: Adding another instance at the top of the screen
NOTE: If you are scrolling your game in other directions then you will want to add your instance at the left, right or bottom of the screen.
Inside your class.move function where we have just added code to remove an instance of the class we need to check if we have less than the minimum instances that we want and if so add another instance.
In this case if there are less than 10 dogs on the screen
if len(dogArray) < 10:
we want to add another, and when we do we want to randomise its x position and set its y postion to the opt of the screen
dogArray.append(dog(random.randrange(10, display_width-50),10))
def move(self):
self.y += 1
if self.y > display_height - 50:
dogArray.remove(self)
if len(dogArray) < 10:
dogArray.append(dog(random.randrange(10, display_width-50),10))