我有一個pygame菜單,我繪製了一些按鈕,代表了我的遊戲的難度。爲了方便用戶,我製作了一個精靈,它指示選擇哪個級別按鈕(將其想象爲按鈕周圍的淺綠色框架)。現在,如果我有一個純色作爲我的背景,我可以用bg顏色填充框架。但我想有一個自定義圖像。但我不知道如何做這個圖像刪除的東西。我不想在每個循環中都做一個surface.blit(bgImage, surface.get_rect())
。有什麼辦法可以告訴pygame只提取圖像的一部分?所以最終結果仍然很好看。這裏是我的代碼,當我有一個顏色作爲背景Pygame blit圖像的一部分(背景圖像)
(請注意,我的問題並不只適用於這種情況下,它更多的是一個圖像的blitting的一般方式,而不必依賴裁剪使用第三方軟件,如油漆(淨值),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在上面的代碼片段中,我沒有包含按鈕類和像顏色,寬度,高度等全局變量,因爲我不認爲它們與我想要的幫兇有關。隨時糾正我的代碼,和/或建議改進。
你看看'blit'中的'area'參數嗎? http://www.pygame.org/docs/ref/surface.html#pygame.Surface.blit – cmd
非常感謝!根據@Cplusplusplus的回答,這是我需要做的。乾杯! –