在 pygame 中使 rect 透明

问题描述

我正在尝试制作一种破砖机,但在围绕球的矩形的透明度方面遇到了问题。每次碰到东西时,您都可以看到矩形。 有什么建议吗?它也迫使我使用白色背景there is an image of the problem

import pygame
pygame.init()
bg_color = (255,255,255)
width,height = 600,400
dx,dy = 2,2
screen = pygame.display.set_mode((width,height))
screen.fill(bg_color)
ball = pygame.image.load("medicine-ball.png").convert()
ball = pygame.transform.scale(ball,(50,50))
ball_rect = ball.get_rect()
ball_color = False
def rect(x1,y1,x2,y2):
    pygame.draw.rect(screen,(0,0),(x1,y2))
game_loop = True
while game_loop:
    event = pygame.event.poll()
    if event.type == pygame.QUIT:
        game_loop = False
    ball_rect = ball_rect.move(dx,dy)
    if ball_rect.left < 0 or ball_rect.right > width:
        dx *= -1
    if ball_rect.top < 0 or ball_rect.bottom > height:
        dy *= -1

    mouse_pos = list(pygame.mouse.get_pos())
    rect(mouse_pos[0]-40,300-10,80,20)
    if ball_rect.bottom == 300 and ball_rect.x > mouse_pos[0]-89 and ball_rect.x < mouse_pos[0]+129:
        dy *= -1
    screen.blit(ball,ball_rect)
    pygame.time.wait(1)
    pygame.display.flip()
    screen.fill(bg_color)

另一件困扰我的事情是我无法改变球的速度,我很确定这是我的 mac 上的问题,因为它可以在我朋友的电脑上运行(这是关于 pygame.time.wait( ))

解决方法

如果要使图像透明,则需要确保设置了图像的 Alpha 通道。此外,您必须使用 convert_alpha() 而不是 convert()

if ball_color:
    ball = pygame.image.load("ball.png").convert_alpha()
else:
    ball = pygame.image.load("medicine-ball.png").convert_alpha()

另见问题的答案:


在pygame中使矩形透明

不幸的是,没有很好的方法来绘制透明的形状。查看问题 Draw a transparent rectangle in pygame 的答案并查看 pygame.draw 模块:

颜色的 alpha 值将直接写入表面 [...],但绘制函数不会透明地绘制。

因此您需要采取一种解决方法:

  1. 创建一个 pygame.Surface 对象,其每像素 alpha 格式足够大以覆盖形状。
  2. 在 _Surface 上绘制形状。
  3. 表面与目标表面混合。 blit() 默认混合 2 个表面

例如3个函数,可以绘制透明的矩形、圆形和多边形:

def draw_rect_alpha(surface,color,rect):
    shape_surf = pygame.Surface(pygame.Rect(rect).size,pygame.SRCALPHA)
    pygame.draw.rect(shape_surf,shape_surf.get_rect())
    surface.blit(shape_surf,rect)

在代码中使用函数而不是 pygame.draw.rectalpha 是 [0,255] 范围内的值:

def rect(x1,y1,x2,y2,alpha = 255):
    #pygame.draw.rect(screen,(0,0),(x1,y2))
    draw_rect_alpha(screen,alpha),y2))