"""
存活一定时间的方块角色
"""
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()
-
- 2026 年 2 月
- 2026 年 1 月
- 2025 年 12 月
- 2025 年 11 月
- 2025 年 10 月
- 2025 年 9 月
- 2025 年 6 月
- 2025 年 5 月
- 2025 年 3 月
- 2025 年 2 月
- 2025 年 1 月
- 2024 年 12 月
- 2024 年 8 月
- 2024 年 6 月
- 2024 年 5 月
- 2024 年 4 月
- 2024 年 3 月
- 2024 年 2 月
- 2023 年 11 月
- 2023 年 9 月
- 2023 年 6 月
- 2023 年 5 月
- 2023 年 4 月
- 2023 年 3 月
- 2023 年 2 月
- 2023 年 1 月
- 2022 年 12 月
- 2022 年 11 月
- 2022 年 10 月
- 2022 年 9 月
- 2022 年 8 月
- 2022 年 7 月
- 2022 年 6 月
- 2022 年 5 月
- 2022 年 4 月
- 2022 年 3 月
- 2022 年 2 月
- 2022 年 1 月
- 2021 年 12 月
- 2021 年 11 月
- 2021 年 10 月
- 2021 年 9 月
- 2021 年 8 月
- 2021 年 7 月
- 2021 年 6 月
- 2021 年 5 月
- 2021 年 4 月
- 2021 年 3 月
- 2021 年 2 月
- 2021 年 1 月
- 2020 年 12 月
- 2020 年 11 月
- 2020 年 10 月
- 2020 年 9 月
- 2020 年 8 月
- 2020 年 7 月
- 2020 年 6 月
- 2020 年 5 月
- 2020 年 4 月
- 2020 年 3 月
- 2020 年 2 月
- 2020 年 1 月
- 2019 年 12 月
- 2019 年 11 月
- 2019 年 10 月
- 2019 年 9 月
- 2019 年 8 月
- 2019 年 7 月
- 2019 年 6 月
- 2019 年 5 月
- 2019 年 4 月
- 2019 年 3 月
- 2019 年 2 月
- 2018 年 3 月
- 2018 年 1 月
- 2017 年 9 月
- 2017 年 5 月
- 2017 年 1 月
