Pygame:尝试像素完美碰撞和图像修改时的分段错误

时间:2018-03-02 01:23:49

标签: segmentation-fault pygame collision-detection mask pixel-perfect

当我将精灵移动到屏幕右侧时,我不断收到分段错误或崩溃。

我试图让我的"精灵"到"切换"我在与面具接触点处有另一个图像的像素,然后在它离开时改回来。目前它做得不太好,分段错误也没有帮助。

此项目的基础是https://www.youtube.com/watch?v=Idu8XfwKUao code.Pylet 所示的基础。在我修改它的地方就是我遇到问题的地方,从while循环开始。根据我的IDE,它与 maskOverlap 变量的设置有关,我认为错误更具体地说是 offset2 变量

所以我的问题是:任何人都可以看到分段错误发生的地点和原因,以及:我可以做些什么来改善我的精灵的结果,然后改变颜色,然后再回来。

import math, random, sys
import cv2
import pygame
from pygame.locals import *

# exit the program
def events():
    for event in pygame.event.get():
        if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
            pygame.quit()
            sys.exit()

# define display surface            
W, H = 900, 600
HW, HH = W / 2, H / 2
AREA = W * H

# initialise display
pygame.init()
CLOCK = pygame.time.Clock()
DS = pygame.display.set_mode((W, H))
pygame.display.set_caption("code.Pylet - Pixel Perfect Collision")
FPS = 120

# define some colors
BLACK = (0, 0, 0, 255)
WHITE = (255, 255, 255, 255)

obstacle = pygame.image.load("obstacle-400x399.png").convert_alpha()
#obstacle = pygame.image.load("mask.jpg").convert_alpha()
obstacle_mask = pygame.mask.from_surface(obstacle)
obstacle_rect = obstacle.get_rect()
ox = HW - obstacle_rect.center[0]
oy = HH - obstacle_rect.center[1]

green_blob = pygame.image.load("greenblob-59x51.png").convert_alpha()
orange_blob = pygame.image.load("orangeblob-59x51.png").convert_alpha()


blob_mask = pygame.mask.from_surface(green_blob)
blob_rect = green_blob.get_rect()
#blob_color = green_blob

# main loop
while True:
    events()

    mx, my = pygame.mouse.get_pos()

    offset = (int(mx - ox), int(my - oy))
    offset2 = (int(ox - mx), int(oy - my))
    result = obstacle_mask.overlap(blob_mask, offset)
    maskOverlap = blob_mask.overlap_mask(obstacle_mask, offset2)
    #blob_temp = blob_color
    maskSize = maskOverlap.get_size()
    a, b = maskSize

    if result:
        blob_color = green_blob.copy()
        for x in range(maskSize[0]):
            for y in range(maskSize[1]):
                if maskOverlap.get_at((x,y)):
                    blob_color.set_at((x,y), orange_blob.get_at((x,y)))

    else:
        blob_color = green_blob

    DS.blit(obstacle, (ox, oy))
    DS.blit(blob_color, (mx, my))

    pygame.display.update()
    CLOCK.tick(FPS)
    DS.fill(BLACK)

0 个答案:

没有答案