我正在尝试编写一个pygame程序,其中用户闪避从屏幕顶部掉落的对象。但是,当我运行时,collideRect会过早激活。有什么建议吗?
import pygame
import sys
import time
import random
pygame.init()
size = width, height = 500, 500
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Avalanche!")
character = pygame.image.load("C:/Python27/Lib/site-packages/StickBasic.png")
boulder = pygame.image.load("C:/Python27/Lib/site-packages/Boulder1.png")
charRect = character.get_rect()
charRect.left = 246
charRect.bottom = 450
running = True
skyBlue = 0, 255, 255
groundBrown = 100, 0, 0
direction = 0
timer = 0
boulderFrequency = 20
boulders = []
def endgame():
global running
running = False
while True:
for e in pygame.event.get():
if e.type == pygame.QUIT:
sys.exit()
def bg():
screen.fill(skyBlue)
pygame.draw.rect(screen, groundBrown, (0, 450, 500, 500))
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
if charRect.left > 0:
direction = -1
elif event.key == pygame.K_RIGHT:
if charRect.right < 500:
direction = 1
elif event.type == pygame.KEYUP:
direction = 0
if (direction < 0) and (charRect.left > 0):
charRect.left -= 1
if (direction > 0) and (charRect.right < 500):
charRect.left += 1
if timer >= boulderFrequency:
timer = 0
newBoulder = {
'rect': pygame.Rect(random.randint(0, 460), -40, 40, 40),
'surface': boulder}
boulders.append(newBoulder)
bg()
for b in boulders:
b['rect'].move_ip(0, 5)
if b['rect'].top > 500:
boulders.remove(b)
for b in boulders:
screen.blit(b['surface'], b['rect'])
screen.blit(character, charRect)
pygame.display.flip()
timer += 1
for b in boulders:
if charRect.colliderect(b['rect']):
endgame()
time.sleep(0.02)
PS:我知道编码不是很干净,但我比较熟悉编码。