# Create a simple box sprite # Draw three instances of the sprite and make them bounce up and down # Task: instead of just dislaying boxes, use the ball.gif image from the website # You'll want to go back to the first tutorial to do this # Uh-oh... one of the balls disappears. Why? Fix it. # Task: Increase the screen size to 400 x 400 # Make sure the balls still bounce off the bottom! # Task: make each box start at a random location # You can set the position of a box on creation # Challenge: can you make the balls bounce at an angle? import sys, os, pygame from pygame.locals import * class Box(pygame.sprite.Sprite): def __init__(self, color, initial_position): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface([15, 15]) self.image.fill(color) # Make our top-left corner the passed-in location. self.rect = self.image.get_rect() self.rect.topleft = initial_position self.going_down = True # Start going downwards self.next_update_time = 0 # update() hasn't been called yet. def update(self, current_time, bottom): # update every 1/100th of a second if self.next_update_time < current_time: # If we're at the top or bottom of the screen, switch directions. if self.rect.bottom == bottom - 1: self.going_down = False elif self.rect.top == 0: self.going_down = True # Move our position up or down by one pixel if self.going_down: self.rect.top += 1 else: self.rect.top -= 1 self.next_update_time = current_time + 10 pygame.init() screen = pygame.display.set_mode([150, 150]) boxes = [] # create a list of box sprites boxes.append(Box([255, 0, 0], [0, 0])) # Make a red box in the top left boxes.append(Box([0, 255, 0], [0, 60])) # Make a green box mid-screen boxes.append(Box([0, 0, 255], [0, 120])) # Make a blue box at the bottom of the creen def input(events): for event in events: if event.type == QUIT: return False return True going = True while going: screen.fill([200, 15, 30]) # set background color time = pygame.time.get_ticks() for b in boxes: # loop over the boxes b.update(time, 150) # update the position of the box screen.blit(b.image, b.rect) # blit each going = input(pygame.event.get()) pygame.display.update() # update the screen pygame.quit()