我想編寫一個程序,當用戶點擊盒子表面的任何地方時,它會顯示隱藏在盒子後面的另一個小盒子。代碼目前還沒有完成。 目前我想做一個動畫,當用戶在屏幕上的任何地方點擊並在包裝小盒子的盒子消失時停止。 這裏是我的代碼:Python 3.5.2 Pygame:盒子揭示動畫
import random, pygame, sys
from pygame.locals import *
pygame.init()
done = False
clock = pygame.time.Clock()
white = (255,255,255) # COLLORS
black = (0,0,0)
red = (255,0,0)
green = (0,100,0)
display_width = 800 # SCREEN DIMMENSION
display_height = 600
game_display = pygame.display.set_mode((display_width,display_height)) # SCREEN
REVEALSPEED = 8
def draw_icon(x,y):
icon = pygame.Rect(x+10,y+10,20,20)
pygame.draw.rect(game_display,red,icon)
def draw_cover(x,y,coverage):
pygame.draw.rect(game_display,white,(x,y,40,40))
draw_icon(x,y)
if coverage > 0:
pygame.draw.rect(game_display, green, (x, y, coverage, 40))
pygame.display.update()
clock.tick(10)
def revealBoxesAnimation(x,y): # Do the "box reveal" animation.
for coverage in range(40, (-REVEALSPEED) - 1, -REVEALSPEED):
draw_cover(x, y, coverage)
def game_loop():
done = False
mouseClicked = False
while done != True:
x = (display_width - 40)/2
y = (display_height - 40)/2
for event in pygame.event.get(): # PRESSED KEYS EFFECTS
if event.type == pygame.QUIT:
done = True
elif event.type == MOUSEBUTTONUP:
mouseClicked = True
mousex, mousey = pygame.mouse.get_pos()
if mousex != None and mousey != None :
if mouseClicked == True :
revealBoxesAnimation(x, y)
game_display.fill(white)
pygame.display.update()
clock.tick(60)
game_loop()
在draw_cover功能我說,該方案只畫出大框,如果「覆蓋」的值大於零。
在revealBoxesAnimation函數中,我使用範圍函數將覆蓋範圍的值從40一直降低到0,一次減少8(40,32,24,16,8,0,-8)。不過,當覆蓋率值爲零時,動畫不會停止。它在無限循環中繼續。
是怎麼回事?
你必須設置'的mouseClicked = FALSE'之後,您就'revealBoxesAnimation' – furas
@furas我總是期待一個複雜的答案,它證明它錯過了一些簡單的...它現在起作用了。非常感謝 ! – ROBlackSnail
'mouse.get_pos()'永不返回'None,None' - 所以'如果mousex!= None和mousey!= None:'總是'True'。 – furas