self.rect = self.image.get_rect()
Done with the Block class. Time to move on to the initialization code.
pygame.init()
screen_width=700
screen_height=400
screen=pygame.display.set_mode([screen_width,screen_height])
block_list = pygame.sprite.Group()
all_sprites_list = pygame.sprite.Group()
We can draw and move all the sprites with one command if they are in a group. We can also check for sprite collisions against an entire group.
for i in range(50):
block = Block(BLACK, 20, 15)
block.rect.x = random.randrange(screen_width)
block.rect.y = random.randrange(screen_height)
block_list.add(block)
all_sprites_list.add(block)
The loop adds 50 black sprite blocks to the screen. Then adds the block to the list of blocks the player can collide with and adds it to the list of all blocks.
player = Block(RED, 20, 15)
all_sprites_list.add(player)
Created a RED player block and added to the all_sprites_list so it can be drawn, but not the block_list.
done = False
clock = pygame.time.Clock()
score = 0
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(WHITE)
pos = pygame.mouse.get_pos()
player.rect.x = pos[0]
player.rect.y = pos[1]
blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True)
This line of code takes the sprite referenced by a player and checks it against all sprites in block_list.
for block in blocks_hit_list:
score +=1
print(score)
This loop checks the list of collisions.
all_sprites_list.draw(screen)
The Group class that all_sprites_list is a member of has a method called “draw”. With only one line of code, a program can cause every sprite in the all_sprites_list to draw.
clock.tick(60)
pygame.display.flip()
pygame.quit()
This lines flip the screen and call the quit method when the main loop is done.
Moving Sprites
Put this in the sprite:
def update(self):
self.rect.y += 1
Put this in the main program loop:
block_list.update()
Practice 1
1. Write the whole code and run.
2. End the game, if all blocks are fallen.
3. Write the result of the game WIN or LOSE depending on the score.
Practice 2
1. Change the black and red blocks to character images.
CHECK YOURSELF
1. What is a Sprite?
a) A function that draws images to the screen.
b) A very bright color that seems to glow.
c) A sprite is to Tinkerbell as a human is to Bob.
d) A graphic image that the computer can easily track, draw on the screen, and detect collisions with.