Pygame Sprite模块入门教程
创作时间:
作者:
@小白创作中心
Pygame Sprite模块入门教程
引用
1
来源
1.
https://geek-docs.com/pygame/pygame-tutorials/t_lib_125_pygame_pygame_sprite_module.html
在Pygame中,任何可以在游戏窗口中绘制的、可以移动的位图都被称为Sprite。pygame.sprite模块包含了游戏开发中有用的类和功能。除了创建精灵对象集合的Sprite类之外,还有一些函数可以实现精灵对象的碰撞。
Sprite类作为游戏中不同对象的基类。你可能需要把一个更多的对象放在组中。为此,也提供了组类。
让我们首先通过子类化 sprite.Sprite
类来开发一个 Sprite 类。这个Block类的每个对象都是一个充满黑色的矩形块。
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()
我们将创建50个块状对象,并把它们放在一个列表中。
for i in range(50):
block = Block(BLACK, 20, 15)
# Set a random location for the block
block.rect.x = random.randrange(screen_width)
block.rect.y = random.randrange(screen_height)
# Add the block to the list of objects
block_list.add(block)
all_sprites_list.add(block)
我们创建一个红色的区块,称为播放器,并把它也添加到列表中。
# Create a RED player block
player = Block(RED, 20, 15)
all_sprites_list.add(player)
在游戏的事件循环中,检测红色块(玩家)随着鼠标的移动与黑色块的碰撞,并计算碰撞次数。
事件循环的代码如下
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# Clear the screen
screen.fill(WHITE)
# Get the current mouse position. This returns the position
# as a list of two numbers.
pos = pygame.mouse.get_pos()
# Fetch the x and y out of the list,
# just like we'd fetch letters out of a string.
# Set the player object to the mouse location
player.rect.x = pos[0]
player.rect.y = pos[1]
# See if the player block has collided with anything.
blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True)
# Check the list of collisions.
for block in blocks_hit_list:
score += 1
print(score)
# Draw all the spites
all_sprites_list.draw(screen)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# Limit to 60 frames per second
clock.tick(60)
pygame.quit()
运行上述代码。移动玩家块来捕捉尽可能多的黑色块。分数将在控制台中显示出来。
热门推荐
月写古诗有哪些——古典诗词中的月亮意象探析
业主与业主之间的称呼方式有哪些?这些称呼如何影响社区关系?
Snøhetta设计的两座建筑:公共空间与个人空间的完美诠释
玻尿酸作用全解析:从保湿到抗衰老的全方位护肤利器
诸葛亮与周瑜联手指挥的卓越才能
给中国“口碑最好的8部动画”排名,《哪吒2》第5,第一杀疯了
揭秘网络流行概念“PUA”:了解它,避免被操纵
AI大模型训练中代理IP的请求成功率监控方法
东北雨姐事件:直播带货的品质之痛
眼睛干涩?灼烧感?可能是干眼症!危害不小,日常做好6个预防
华语乐坛的16个音乐组合,知道三个你就老了
华语乐坛的16个音乐组合,知道三个你就老了
心梗来临前的6个预警信号!记住这些,关键时刻能救命
鸡蛋和鱼引发过敏如何处理
心理亚健康:定义、成因与改善方法
Docker如何部署多台机子
做数字人怎么赚钱
汉文帝登基初期如何巩固皇权?
服务器性能如何评估,关键指标与最佳实践是什么?
四川养牛品种及牧草推荐指南
男生学徒最好的十大行业 学什么手艺吃香
电子行业温控风冷式配电柜设计与应用
用50/30/20法则,开启你的财富管理第一步!
东莞职业技术学院2025年招生简章(含招生计划、录取分数线)
含氟牙膏与不含氟牙膏:哪个更适合你?
土地使用权分摊面积怎么计算
同步带轮的氮化表面处理?
钢材热处理之经氮化处理,软氮化和硬氮化的区别和作用是什么?
使用阿达帕林凝胶期间的护肤品选择指南
春日焕新颜,养发黄金季:不可不知的春季护发秘籍