""" 存活一定时间的方块角色 """ import pygame import random class Square(pygame.sprite.Sprite): """继承自pygame.sprite.Sprite的Square类""" def __init__(self, pos, *groups): super().__init__(*groups) self.image = pygame.Surface((50, 30)) self.image.fill(pygame.Color('cyan')) self.rect = self.image.get_rect(center=pos) self.timer = None self.dx = random.randint(-5,5) self.dy = random.randint(-5,5) def move(self): """移动矩形""" self.rect.move_ip(self.dx/10,self.dy/10) def update(self): """更新自己""" self.move() if self.timer is not None: # 计时器启动了,那么开始计时,超过1500毫秒就自杀 if pygame.time.get_ticks() - self.timer >= 1500: self.kill() screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption("存活一定时间的方块角色") squares = pygame.sprite.Group() # 所有的方块组 方块 = Square((320, 240), squares) # 新建一个方块 running = True clock = pygame.time.Clock() # 新建时钟对象 while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: # 按任意键开始计时 方块.timer = pygame.time.get_ticks() squares.update() screen.fill((30, 30, 30)) squares.draw(screen) pygame.display.flip() clock.tick(30) pygame.quit()
本站所有作品,教程等皆为原创,版权所有。只供个人及单位内部研究使用,对外展示或传播必需经本站同意,且注明来自本站。培训机构等用本站资源培训学生,需经本站授权。一旦付款,表示同意本站知识付费原则:数字商品,不支持退款。亦可直接向微信号scratch8付款购买。入住QQ群:225792826 和爱好者共同交流,并且能下载免费提供的Python资源(需提供真实姓名才可入群)
李兴球的博客_Python创意编程技术前沿_pygame » 存活一定时间的方块角色
李兴球的博客_Python创意编程技术前沿_pygame » 存活一定时间的方块角色