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()
    
相关推荐
上半场结束,中场已休息,下半场ing4 天前
2222222
pygame
hhcgchpspk5 天前
python实现音频淡入淡出功能
python·程序人生·音视频·pygame
叫我:松哥7 天前
基于python强化学习的自主迷宫求解,集成迷宫生成、智能体训练、模型评估等
开发语言·人工智能·python·机器学习·pygame
薛定谔的猫喵喵12 天前
基于Python+PyGame实现的一款功能完整的数独游戏,支持多难度选择、实时验证、提示系统、成绩记录,并采用多线程优化加载体验。(文末附全部代码)
python·游戏·pygame
玖疯子13 天前
TCP/IP协议栈深度解析技术文章大纲
python·scikit-learn·pyqt·pygame
HarmonLTS14 天前
Pygame动画制作进阶(可直接运行,附核心原理)
python·pygame
百锦再15 天前
国产数据库现状与技术演进
数据库·python·plotly·flask·virtualenv·pygame·tornado
企业对冲系统官15 天前
大宗商品风险对冲系统统计分析功能的技术实现
运维·python·算法·区块链·github·pygame
智算菩萨15 天前
【Python小游戏】深度解析Pygame实现2048游戏的完整开发流程(有代码实现)
python·游戏程序·pygame
4***175419 天前
Python 小游戏实战:打造视觉精美的数独小游戏
开发语言·python·pygame