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()
运行上述代码。移动玩家块来捕捉尽可能多的黑色块。分数将在控制台中显示出来。
热门推荐
学行政管理好就业吗?
《幽游白书》中户愚吕:一个令人难忘的反派角色
2025考研英语目标分数?一文解读各分数段目标院校!
成都公积金封存提取指南及贷款流程详解
成都住房公积金提取指南:条件、额度、资料与方法详解
医生提醒:消炎药不宜空腹服用,否则可能伤胃
磨牙的医学原因是什么,如何进行治疗
消炎药不能盲目吃 6个注意事项要知道
互联网大厂纷纷发布通报:零容忍!辞退,移送公安
用人单位该如何辞退违反劳动纪律的员工
雷鬼音乐的起源和特征:历史、演变和全球影响
NMPA认证是什么?详解中国药品监督管理局认证体系
CPU的核心制造工艺:BGA封装技术
泥胡菜:一种兼具食用与药用价值的野生植物
了解作业指导书(SOP),看这一篇就够了!(附SOP流程图制作规范)
负热量食物吃再多也不会长胖吗
硬核拆解华为/大疆/小米硬件面试真题:手撕电路+考点思维导图(附答案)
伤口上撒盐能消毒吗?三甲医院教您如何正确处理烧/烫伤
配方奶泡好保温可以放多久?奶粉浓度泡错与结块能喝吗?婴儿喝羊奶粉的好处?
如何提升API接口的并发能力
“拉萨天团”大战游资!人气牛股尾盘“地天板”,近期龙虎榜单速览,这些席位已成常客
负卡路里的食物有哪些
立方体的计算与应用:从基础知识到实际生活中的趣味探索
最佳路线:和朋友黄山游玩四天三晚攻略
中国人有自己的“沙拉”!它真的能减脂?
小町米和长粒香米:口感特点与优质东北大米推荐
马斯克的十大创新思维理论:如何激发你的无限潜能
厦门旅游美食攻略:探寻地道小吃与特色美食全指南
韦伯望远镜在主小行星带探测到138颗直径只有十米左右的小行星
【“沂”案释法 小案大义】探望权是权利还是义务?是否可以放弃?