Pygame中Sprite的使用方法6-6

4 重新绘制界面

每次碰撞发生后,程序界面需要重新绘制,代码如下所示。

python 复制代码
screen.fill(WHITE)
all_sprites_list.draw(screen)
pygame.display.flip()

其中,screen表示程序的整个界面,将其绘制为白色背景;之后通过all_sprites_list.draw()绘制碰撞后剩下的方块(碰撞的方块已经在group中删除);最后显示重新绘制的内容。

5 完整代码

以上程序的完整代码如下所示。

python 复制代码
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()
    
相关推荐
chushiyunen20 小时前
python pygame实现贪食蛇
开发语言·python·pygame
听风吹等浪起3 天前
用Python和Pygame从零实现坦克大战
开发语言·python·pygame
智算菩萨3 天前
【Pygame】第8章 文字渲染与字体系统(支持中文字体)
开发语言·python·pygame
智算菩萨3 天前
【Pygame】第20章 从0到1构建贪吃蛇:基于Pygame的游戏架构与状态机设计实战(有超详细中文注释)
python·游戏·pygame
智算菩萨3 天前
【Pygame】第23章 平台跳跃游戏:基于有限状态机的2D平台物理模拟与摄像机视口管理系统(有超详细中文注释供大家学习)
python·游戏·pygame
智算菩萨4 天前
【Pygame】第10章 游戏状态管理与场景切换机制
python·游戏·pygame
智算菩萨4 天前
【Pygame】第15章 游戏人工智能基础、行为控制与寻路算法实现
人工智能·游戏·pygame
智算菩萨4 天前
【Pygame】第17章 游戏用户界面系统与菜单交互设计实现
游戏·ui·pygame
智算菩萨4 天前
【Pygame】第19章 网络多人游戏基础与局域网联机原理
网络·python·游戏·pygame
智算菩萨4 天前
【Pygame】第16章 游戏存档系统设计与数据持久化实现
jvm·游戏·pygame