我对编程很陌生,最近我决定启动Pygame。根据我发现的教程,我创建了这个游戏。目的是观察球弹跳并通过在适当的时间点击使其远离底部的盒子。我知道代码有点混乱,但最大的问题是虽然代码运行,但当球和盒子碰到时,游戏并没有退出。
import sys, pygame
pygame.init()
size = width, height = 320, 240
speed = [2, 2]
black = 0, 0, 0
screen = pygame.display.set_mode(size)
ball = pygame.image.load("ball.bmp")
target = pygame.image.load("square_target.bmp")
ballrect = ball.get_rect()
clock = pygame.time.Clock()
target_place = [160, 200]
fps = 60
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
if pygame.mouse.get_pressed()[0]:
speed[0] = -speed[0]
if ballrect <= target_place[0] + 50 or ballrect <= target_place[1] + 50:
pygame.event.post(pygame.QUIT)
screen.fill(black)
screen.blit(ball, ballrect)
screen.blit(target, target_place)
pygame.display.flip()
fps += 0.01
print (fps)
clock.tick(fps)
任何帮助?
答案 0 :(得分:6)
Pygame包含一个内置方法来检查两个矩形是否重叠。因此,如果这种情况属实:
ballrect.colliderect(target.get_rect())
...这意味着两个图像重叠。