0

我对编程很陌生,最近我决定开始 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)

有什么帮助吗?

4

1 回答 1

6

Pygame 包含一个内置方法来检查两个矩形是否重叠。因此,如果这个条件为真:

ballrect.colliderect(target.get_rect())

...这意味着两个图像重叠。

于 2013-09-12T18:41:01.587 回答