Pygame Erasing Images on Backgrounds

ε祈祈猫儿з 提交于 2019-12-19 10:02:21

问题


You blit an image onto your surface to use as your background. Then you press button X to blit an image on the same surface, how do you erase the image? I have this so far, but then I end up with a white rectangle in the middle of my background.

screen = pygame.display.set_mode(1280, 512)

screen.blit(background, (0,0))

while True:   
    pygame.display.flip() #flip is same as update
    for event in pygame.event.get():
        if (event.type == pygame.KEYDOWN):        
            if event.key == pygame.K_SPACE:
                screen.blit(player, (x, y))
            if event.key == pygame.K_BACKSPACE:
                pygame.draw.rect(screen, [255,255,255], (x, y, 62,62))

回答1:


There are basically two things you can do here. You can go the simple route and just draw the background again...

if event.key == pygame.K_BACKSPACE:
   screen.blit(background, (0,0))

Or, if you want it to be a little more efficient, you can have the blit method only draw the part of the background that the player image is covering up. You can do that like this...

screen.blit(background, (x, y), pygame.Rect(x, y, 62, 62))

The Rect in the third argument will cause the blit to only draw the 62x62 pixel section of 'background' located at position x,y on the image.

Of course this assumes that the player image is always inside the background. If the player image only partially overlaps the background I'm not entirely sure what will happen. It'll probably throw an exception, or it'll just wrap around to the other side of the image.

Really the first option should be just fine if this is a fairly small project, but if you're concerned about performance for some reason try the second option.




回答2:


Normally the blit workflow is just to blit the original background to screen.

In your code you would use screen.blit(background, (0,0))

When you start combining lots of surfaces you will probably want either a variable or a list of variables to keep track of screen state.

E.g.

Initialise Background

objectsonscreen = []
objectsonscreen.append(background)
screen.blit(background, (0,0))

Add Sprite

objectsonscreen.append(player)
screen.blit(player, (x, y))

Clear Sprite

objectsonscreen = [background]
screen.blit(background, (0,0))

See here for more information on sprites in Pygame. Note that if your background isn't an image background and is just a solid color you could also use screen.fill([0, 0, 0]) instead.



来源:https://stackoverflow.com/questions/9286738/pygame-erasing-images-on-backgrounds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!