• pygame 方块随机飞舞动画


    import pygame
    import random
    # default
    WIDTH=1280
    HEIGHT=1060
    FPS=60
    sum=0
    # set color
    WHITE=(255,255,255)
    BLACK=(0,0,0)
    RED=(255,0,0)
    GREEN=(0,255,0)
    BLUE=(0,0,255)
    color=[WHITE,RED,GREEN,BLUE]
    # set Block class
    class Block(pygame.sprite.Sprite):
        def __init__(self):
            pygame.sprite.Sprite.__init__(self)
            self.image=pygame.Surface((50,50))
            self.image.fill(random.choice(color))
            self.rect = self.image.get_rect()
            self.rect.center=(random.randint(1,WIDTH),random.randint(1,HEIGHT))
            self.ce=random.randint(1,2)
            self.speed=random.choice([i for i in range(-20,20) if not i in range(-5,5)])
        def update(self):
            if self.ce==1:
                self.rect.x+=self.speed
            else:
                self.rect.y+=self.speed
    # pygame init
    pygame.init()
    screen=pygame.display.set_mode((WIDTH,HEIGHT))
    pygame.display.set_caption('lowb cartoon')
    clock = pygame.time.Clock()
    #set group
    all_sprites = pygame.sprite.Group()
    block1=[Block() for i in range(random.randrange(20,40))]
    block2=[Block() for i in range(random.randrange(20,40))]
    #block=Block()
    #print(block.ce,block.speed)
    all_sprites.add(block1)
    all_sprites.add(block2)
    # main loop
    running=True
    while running:
        sum+=1
        if sum%100==0:
            block1=[Block() for i in range(random.randrange(20,40))]
            all_sprites.add(block1)
        if sum%150==0:
            block2=[Block() for i in range(random.randrange(20,40))]
            all_sprites.add(block2)
        #set FPS
        clock.tick(FPS)
        #set event
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running=False
        #set update
        all_sprites.update()
        #set draw/render
        screen.fill(BLACK)
        all_sprites.draw(screen)
        #flip time
        pygame.display.flip()
    pygame.quit()
    
  • 相关阅读:
    2020软件工程作业04
    2020软件工程作业03
    2020软件工程作业02
    2020软件工程作业01
    2020软件工程作业02
    2020软件工程作业01
    WEB学习路线2019完整版(附视频教程+网盘下载地址)
    (2018干货系列七)最新大数据学习路线整合
    (2018干货系列六)最新云计算学习路线整合
    (2018干货系列五)最新UI设计学习路线整合
  • 原文地址:https://www.cnblogs.com/baccano-acmer/p/10255057.html
Copyright © 2020-2023  润新知