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()
运行上述代码。移动玩家块来捕捉尽可能多的黑色块。分数将在控制台中显示出来。
热门推荐
揭秘废品回收行业:从分类到处理的全流程解析
聂耳故居:音乐伟人的诞生之地
未成年人能否放弃继承权?法律专家解读
量比指标的定义是什么?量比指标在股票交易中的实际应用有哪些?
电脑无法连接WiFi?试试这些实用解决方案
眼科与视功能检查-立体视觉功能检查
肝不好,身体会变臭?闻到这3种异味要留心了
喷墨打印机丨热发泡VS微压电 谁更顺应当下市场环境?
民工工资专户流程全面解析
优化问卷设计流程,实现数据高效收集
心理科普 | 空船效应
2024年中国人工智能行业市场规模达6964亿元 北京市场份额占30%
微波炉加热鸡蛋新技能get!注意这几点,美味又安全!
全球最深矿井至地下4350米,深度相当于7个广州小蛮腰
多模态大型语言模型的语义对齐技术研究
不同类型甲状腺癌远处转移的影响因素、风险和器官概率
龙岗区多场春风行动招聘会:AI人才需求猛增,线上线下吸引超万人求职
第十五届华语科幻星云奖揭晓,刘洋获长篇小说金奖
相关性分析热图:ggplot2包绘制环境因子和物种相关性热图/气泡图
期刊投稿时邮件怎么写
重大老师科幻小说获华语科幻星云奖金奖!
Web3的盈利模式:从DApps到DAO的全方位解析
如何用热阻测试仪T3Ster测试IC的热特性
浙江统招专升本数学考试范围解析!
武汉樱花:春日限定的浪漫宝藏地
国际转运是先清关还是先提柜?
装空调为什么要抽真空?一文读懂空调安装中的抽真空环节
狗狗呕吐后应该吃什么(饮食安排让宠物更舒适)
急性等容血液稀释:一种安全有效的自体输血技术
互不相容与互相独立的区别