嗨,据我所知,我正在用玩偶做一个破砖游戏。
pygame.sprite.spritecollide(ball, block_list, True, pygame.sprite.collide_mask)这一部分确认了sprite组与sprite之间的碰撞,并从block_list中移除了碰撞的块对象。
为了更容易地看到与球的碰撞,这段代码允许球与鼠标自由移动,我认为用"print(block_list)“从组中移除被撞的墙壁,但是屏幕上的砖块没有被移除。
当球击中砖块时,如何使砖块从屏幕上脱落?
import pygame
import random
class Block(pygame.sprite.Sprite):
def __init__(self, img):
pygame.sprite.Sprite.__init__(self)
self.image = img
self.rect = img.get_rect()
pygame.init()
screen = pygame.display.set_mode((940, 768))
stickimage = pygame.image.load('stick.png')
stick = stickimage.get_rect()
stick.center = (500, 700)
background = pygame.Surface(screen.get_size())
pic = [pygame.image.load("half/brick1.png").convert_alpha(), pygame.image.load("half/brick2.png").convert_alpha(),
pygame.image.load("half/brick3.png").convert_alpha(), pygame.image.load("half/brick4.png").convert_alpha()]
block_list = pygame.sprite.Group()
for j in range(0, 5):
for i in range(0, 7):
block = Block(pic[random.randrange(4)])
block.rect.x = i * 135
block.rect.y = j * 30
block.mask = pygame.mask.from_surface(block.image)
block_list.add(block)
ball_pic = pygame.image.load("ball.png").convert_alpha()
ball = Block(ball_pic)
ball.rect.center = (500, 500)
ball.mask = pygame.mask.from_surface(ball.image)
ball.radius = 23
score = 0
done = True
while done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = False
if event.type == pygame.MOUSEMOTION:
ball.rect.center = event.pos
break
hit_list = pygame.sprite.spritecollide(ball, block_list, True, pygame.sprite.collide_mask)
for h in hit_list:
score += 1
print(block_list)
print(hit_list)
block_list.draw(background)
screen.blit(background, (0, 0))
screen.blit(ball.image, ball.rect)
screen.blit(stickimage, stick)
pygame.display.flip() 发布于 2020-07-07 18:38:24
我建议将雪碧的pygame.Surface转换为具有convert_alpha()的曲面。可以在Sprite对象的构造函数中创建mask属性:
class Block(pygame.sprite.Sprite):
def __init__(self, img):
pygame.sprite.Sprite.__init__(self)
self.image = img.convert_alpha() # <----
self.rect = img.get_rect()
self.mask = pygame.mask.from_surface(self.image) # <----无论如何,主要的问题是,你在背景表面而不是窗口表面上画砖块:
block_list.draw(background) 背景表面永远不会被清除。在窗口中绘制背景,然后在背景顶部绘制砖块:
while done:
# [...]
screen.blit(background, (0, 0))
block_list.draw(screen)
screen.blit(ball.image, ball.rect)
screen.blit(stickimage, stick)
pygame.display.flip() https://stackoverflow.com/questions/62780936
复制相似问题