學習總結-《父與子的編程之旅》chapter 17


本章學習動畫精靈和碰撞檢測。

import  sys,pygame
from random import *

class MytagClass(pygame.sprite.Sprite):
    def __init__(self,image_file,location,speed):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(image_file)
        self.rect = self.image.get_rect()
        self.rect.left,self.rect.top = location
        self.speed = speed

    def move(self):
        self.rect = self.rect.move(self.speed)
        if self.rect.left<0 or self.rect.right >width:
            self.speed[0] = -self.speed[0]
        if self.rect.top <0 or self.rect.bottom>height:
            self.speed[1] = -self.speed[1]

def animate(group):
        screen.fill([255,255,255])
        for ball in  group:#動畫精靈組法 或者常規python列表法
            ball.move() #先完成所有移動
        for ball in group:
            group.remove(ball)
            if pygame.sprite.spritecollide(ball,group,False):
                ball.speed[0] = -ball.speed[0]
                ball.speed[1] = -ball.speed[1]

            group.add(ball)
            #ball.move() 一個一個移動、檢測碰撞 導致顫抖
            screen.blit(ball.image,ball.rect)
        pygame.display.flip()
 # pygame.time.delay(20)


size = width,height = 1024,1024
screen = pygame.display.set_mode(size)
screen.fill([255,255,255])
img_file = "imagetag.jpg"
clock = pygame.time.Clock()
group = pygame.sprite.Group()
for row in range(0,2):
    for column in range(0,2):
        location = [column*550+100,row*450+50]
        speed = [choice([5,-5]),choice([5,-5])]
        ball =MytagClass(img_file,location,speed)
        group.add(ball)


running =True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            frame_rate = clock.get_fps()
            print ("frame rate = ",frame_rate)
    animate(group)
    clock.tick(30)
pygame.quit()


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com