4 인터페이스 다시 그리기
충돌이 발생할 때마다 프로그램 인터페이스를 다시 그려야 하며 코드는 다음과 같습니다.
screen.fill(WHITE)
all_sprites_list.draw(screen)
pygame.display.flip()
그 중 screen은 프로그램의 전체 인터페이스를 나타내며 흰색 배경으로 그려지고 충돌 후 남은 블록은 all_sprites_list.draw()를 통해 그려지고(충돌된 블록은 그룹에서 삭제됨) 마지막으로 다시 그려진 내용이 표시됩니다.
5개의 완전한 코드
위 프로그램의 전체 코드는 아래와 같습니다.
import pygame, random
from pygame.locals import *
class Block(pygame.sprite.Sprite):
def __init__(self, color, width, height):
super().__init__()
self.image = pygame.Surface((width, height))
self.image.fill(color)
self.rect = self.image.get_rect()
GREEN = (0, 255, 0)
RED = (255, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
screen_width = 1000
screen_height = 600
done = False
score = 0
clock = pygame.time.Clock()
pygame.init()
screen = pygame.display.set_mode((screen_width, screen_height))
block_list = pygame.sprite.Group()
all_sprites_list = pygame.sprite.Group()
block_bad_list = pygame.sprite.Group()
for i in range(50):
block = Block(GREEN, 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)
for i in range(10):
block = Block(RED, 20 ,15)
block.rect.x = random.randrange(screen_width)
block.rect.y = random.randrange(screen_height)
block_bad_list.add(block)
all_sprites_list.add(block)
player = Block(BLUE, 20, 15)
all_sprites_list.add(player)
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)
for block in blocks_hit_list:
score += 1
print('当前分数为:'+str(score))
blocks_hit_list = \
pygame.sprite.spritecollide(player, block_bad_list, True)
for block in blocks_hit_list:
score -= 1
print('当前分数为:'+str(score))
all_sprites_list.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()