pygame像素级碰撞检测示例程序_pygame_pixel_collision_check

"""pygame像素级碰撞检测示例程序

采用mask的碰撞检测,提取像素后可用于像素级撞检测,pygame_pixel_collision_check by lixingqiu
"""


import pygame, time
from pygame.locals import *


class Sprite(pygame.sprite.Sprite):

    def __init__(self, imagefile, screen, pos):
        """
          初始化角色,imagefile:图像文件名,screen:所在屏幕,pos:左上角坐标
        """
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(imagefile)
        self.rect = self.image.get_rect()
        self.rect.topleft = pos
        self.screen = screen         
        self.speed = [0 ,0]    # 水平和垂直方向位移向量
       

    def update(self):
        """原地更新矩形坐标"""
        self.rect.move_ip(self.speed[0],self.speed[1])

def main():
    """主要调用函数"""
    pygame.init()
    width, height = 600, 600
    # 创建一个屏幕
    screen = pygame.display.set_mode((width, height))
    pygame.display.set_caption('采用mask的碰撞检测,提取像素后可用于像素级撞检测pygame_pixel_collision_check by lixingqiu')
    image_list = ['maze.png', 'player.png']
    sprite_group = pygame.sprite.Group()
   
    pos_list = [(0, 0), (0, 150)]
    # 生成精灵   
    maze = Sprite(image_list[0], screen, pos_list[0])        
    sprite_group.add(maze)
    
    sprite = Sprite(image_list[1], screen, pos_list[1])        
    sprite_group.add(sprite)
    
    clock = pygame.time.Clock()
    running = True    
    
    while running:        
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
            # 上下左右移动
            if event.type == KEYDOWN:
                if event.key == K_RIGHT:
                    sprite.speed = [10 ,0] 
                     
                elif event.key == K_LEFT:        
                    sprite.speed = [-10 ,0] 
                     
                elif event.key == K_UP:                   
                    sprite.speed = [0 ,-10] 
                     
                elif event.key == K_DOWN:                   
                    sprite.speed = [0 ,10]
                    
            elif event.type == KEYUP:               
                    sprite.speed = [0 ,0]                

        sprite_group.update()             # 更新坐标等。
        
        # 使用mask进行碰撞检测,返回坐标点
        point = pygame.sprite.collide_mask(maze,sprite)
        if point:
            pixel = maze.image.get_at(point)
            print("碰撞点:",point)
            print("像素值:",pixel)
            info = "碰撞点:" + str(point) + "|像素值:" + str(pixel)
            pygame.display.set_caption(info)
            sprite.speed[0] = -1 * sprite.speed[0]
            sprite.speed[1] = -1 * sprite.speed[1]
                    
       
        screen.fill((255, 255, 255))
        sprite_group.draw(screen)
        pygame.display.update()
        clock.tick(30)
    pygame.quit()

if __name__ == '__main__':
    main()