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()
    
相关推荐
中文Python1 天前
小白中文Python-db_桌面小黄鸭宠物
数据库·python·pygame·宠物·中文python·小白学python
高洁014 天前
【无标题】大模型-扩散模型(Diffusion Model)原理讲解(3)
人工智能·python·神经网络·pygame
IT教程资源9 天前
(免费分享)基于python的飞机大战游戏
python·游戏·pygame
棉猴9 天前
Pygame中实现图像旋转效果-应用2-1
python·pygame·游戏编程·图像旋转·rotate
pop_opo_12 天前
使用 Python + Pygame 键盘控制无人机(AirSim)
python·无人机·pygame
百锦再14 天前
一文掌握Flask:从基础使用到高级应用
后端·python·django·flask·virtualenv·scikit-learn·pygame
Kaaras15 天前
Python如何开发游戏
python·游戏·pygame
百锦再24 天前
[特殊字符] Python在CentOS系统执行深度指南
开发语言·python·plotly·django·centos·virtualenv·pygame
yzx99101324 天前
接口协议全解析:从HTTP到gRPC,如何选择适合你的通信方案?
网络·人工智能·网络协议·flask·pygame
念念不忘 必有回响1 个月前
Pygame模块化实战:从零构建Aliens射击游戏全流程(一)
python·游戏·pygame