【发布时间】:2015-12-23 06:24:44
【问题描述】:
我有一个 pygame 菜单,我在其中绘制了一些按钮,这些按钮代表了我的游戏的关卡难度。为方便用户,我制作了一个精灵,指示选择了哪个级别按钮(将其视为按钮周围的浅绿色框)。现在,如果我有纯色作为背景,我可以用 bg 颜色填充框架。但我想要一个自定义图像。但是我不确定如何用这张图片删除东西。我不想做一个surface.blit(bgImage, surface.get_rect())
在每个while循环中。有没有办法告诉 pygame 只对图像的一部分进行 blit?所以最终的结果还是好看的。当我有颜色作为背景时,这是我的代码
(请注意,我的问题不仅适用于这种情况,它更像是一种对图像的一部分进行 blitting 的一般方法,而不必依赖于使用 3rd 方软件(如paint(net)、photoshop)裁剪图像等):
#class for the highlight sprite that appears when a level button is clicked
class HighLightImage(Sprite):
def __init__(self, spriteX, spriteY, width = 180, height = 60):
Sprite.__init__(self)
self.rect = pygame.Rect(spriteX, spriteY, width, height)
self.image = pygame.image.load("highlight.png")
#function to draw the highlight sprite, after deleting its older position.
def draw(self, newSpriteX, newSpriteY):
#due to technical issues the following method is using 4 dirty sprite deletions.
surface.fill(bgCol, (self.rect.x, self.rect.y, self.rect.width, 10))
surface.fill(bgCol, (self.rect.x, self.rect.y + self.rect.height-10, self.rect.width, 10))
surface.fill(bgCol, (self.rect.x, self.rect.y, 10, self.rect.height))
surface.fill(bgCol, ( self.rect.x + self.rect.width-10, self.rect.y, 10, self.rect.height))
self.rect.x = newSpriteX
self.rect.y = newSpriteY
surface.blit(self.image, self.rect)
这是主要的while循环
def mainIntro():
#snake image
snakeImg = pygame.image.load("snakeB.png")
snakeImg = pygame.transform.scale(snakeImg, (150,200))
#highlight obj
hlObj = HighLightImage(0, 0)
#starting level = 1
levels = 1
#initial fill
surface.fill(bgCol)
intro = True
#start button
startButton = StartButton(WIDTH/2-330, HEIGHT - 150)
startButton.draw("Start")
#Exit button
exitButton = ExitButton(WIDTH/2+110, HEIGHT - 150)
exitButton.draw("Exit")
#level buttons
easyLvl = EasyLevelButton( 65, HEIGHT/2 )
easyLvl.draw("Easy")
midLvl = MediumLevelButton( 320, HEIGHT/2 )
midLvl.draw("Medium")
hardLvl = HardLevelButton( 570, HEIGHT/2 )
hardLvl.draw("Hard")
instructions()
surface.blit(snakeImg, (WIDTH/2-75, HEIGHT - 250))
while intro:
for ev in pygame.event.get():
# X exit event
if ev.type == QUIT:
pygame.quit()
sys.exit()
if ev.type == MOUSEMOTION:
startButton.hover()
exitButton.hover()
easyLvl.hover()
midLvl.hover()
hardLvl.hover()
if ev.type == MOUSEBUTTONDOWN:
if easyLvl.clicked():
levels = 1
if midLvl.clicked():
levels = 2
if hardLvl.clicked():
levels = 4
#button exit event
elif exitButton.clicked():
pygame.quit()
sys.exit()
elif startButton.clicked():
intro = False
#highlight frame, according to level-button chosen
if levels == 1:
hlObj.draw(easyLvl.x-10, easyLvl.y-10)
elif levels == 2:
hlObj.draw(midLvl.x-10, midLvl.y-10)
elif levels == 4:
hlObj.draw(hardLvl.x-10, hardLvl.y-10)
update()
return levels
P.s 在上面的代码 sn-ps 中,我没有包含按钮类,以及颜色、宽度、高度等全局变量,因为我认为它们与我想要的共犯无关。随时更正我的代码,和/或提出改进建议。
【问题讨论】:
-
您是否考虑过在
blit中使用area参数? pygame.org/docs/ref/surface.html#pygame.Surface.blit -
非常感谢伙计!根据@Cplusplusplus 的回答,您的回答是我需要做的。干杯!