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()
运行上述代码。移动玩家块来捕捉尽可能多的黑色块。分数将在控制台中显示出来。
热门推荐
小红书如何设置权限:提升隐私与个性化体验的终极指南
象棋入门必修课:从基础规则到实战玩法全解析
华中师范大学是一本还是二本?2024年本科最低590分录取
香港户口迁回内地指南:最新政策与办理流程详解
贵州百里杜鹃旅游攻略2025(最佳时间+门票价格+最佳地点+活动安排)
探秘“万岁”:一词之源,千古之颂
揭秘:20个字的“女”字加一笔后,竟有这些变化!
右踝距腓前韧带损算工伤吗
甩棍是违禁品吗?能不能携带过安检?
宝石:地质学中独特的光学效应
伊纳里多电影的叙事手法:多方位融合的叙述者话语与叙事视角
临期商品受欢迎:产品可以临期,安全不能打折
电脑云盘如何读取内存卡
韩式烤肉各类酱料秘方,从腌制到蘸料的完整教程
公里如何算法
明朝开国名将冯胜:从战功赫赫到功高震主
古代时间的叫法是什么?解析古代常用的时间单位和叫法
吃冬虫夏草能喝酒吗?服用冬虫夏草期间饮酒可能影响其药效的发挥
空调插座和普通插座的区别及选购注意事项
肖永红教授:链球菌感染的研究进展
水粉颜料弄衣服上怎么洗掉
抑郁用药一文全了解
理财中的风险因素有哪些?这些风险因素如何进行评估和管理?
普洱茶减肥喝生茶还是熟茶 减肥效果哪个更好?
舌头溃疡怎么快速愈合
38.7℃要吃退烧药吗
朝韩全州李氏家族的基因溯源研究
红茶水能存放多久:如何判断变质与饮用期限?
如何把握技术的投资机会
《红楼梦》中的刘姥姥:底层人的无奈幽默