2017-08-08 76 views
0

如何在不使用精灵类的情况下将图像转换为pygame中的另一图像?另外,如何在将其转换为另一张图像后删除之前的图像?我不知道你通过删除图像的意思到底是什么如何将表面(图像)转换成pygame中的另一个表面?

+0

你究竟想要做什么? – skrx

+0

将表面转换为另一个表面意味着什么?更改为新格式?你能向我们展示一个你尝试过的代码的例子,它可能会更清晰。 –

回答

0

我今天写了一个小程序,演示了如何切换对象图像(它可以帮助/回答您的问题)。它对大多数代码的使用有记录,所以更容易理解它的工作原理和原理(据我所知,任何人都可以在昨天开始编程)。

总之,这里是代码:

import pygame, sys 

#initializes pygame 
pygame.init() 

#sets pygame display width and height 
screen = pygame.display.set_mode((600, 600)) 

#loads images 
background = pygame.image.load("background.png").convert_alpha() 

firstImage = pygame.image.load("firstImage.png").convert_alpha() 

secondImage = pygame.image.load("secondImage.png").convert_alpha() 

#object 
class Player: 
    def __init__(self): 

     #add images to the object 
     self.image1 = firstImage 
     self.image2 = secondImage 

#instance of Player 
p = Player() 

#variable for the image switch 
image = 1 

#x and y coords for the images 
x = 150 
y = 150 

#main program loop 
while True: 

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

    #places the image selected 
    if image == 1: 
     screen.blit(p.image1, (x, y)) 
    elif image == 2: 
     screen.blit(p.image2, (x, y)) 

    #checks if you do something 
    for event in pygame.event.get(): 

     #checks if that something you do is press a button 
     if event.type == pygame.KEYDOWN: 

      #quits program when escape key pressed 
      if event.key == pygame.K_ESCAPE: 
       sys.exit() 

      #checks if down arrow pressed 
      if event.key == pygame.K_DOWN: 

       #checks which image is active 
       if image == 1: 

        #switches to image not active 
        image = 2 

       elif image == 2: 

        image = 1 

    #updates the screen 
    pygame.display.update() 

我不知道你的代码是如何设置的,或者如果这是你需要什么(我并不完全理解类要么所以它可能是一个精灵类),但我希望这有助于!

0

转换一个图像到另一个是重新分配变量

firstImage = pygame.image.load("firstImage.png") 
secondImage = pygame.image.load("secondImage.png") 

firstImage = secondImage 

del secondImage 

一样简单。您可以使用“del secondImage”来删除代码中的引用并将其发送到垃圾回收。一旦你清除了屏幕并使更新后的图像闪烁,应该不再有任何过时图像的标志。

相关问题