如何在Rect与Rect碰撞时测试Python | Pygame的

时间:2014-10-26 16:34:30

标签: python pygame

我知道你可能认为它有点像副本,但事实并非如此。这不是使用类,而是完全基于pygame而不是import os。我需要检测这两个矩形是否发生碰撞,并在代码中用注释发出信号。

这是代码: 的Python:

import pygame, sys, time, random
from pygame.locals import *

pygame.init()

fpsClock = pygame.time.Clock()


playSurface = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Bob the Block goes Skiing')

redColour = pygame.Color(252, 0, 6)

blackColour = pygame.Color(0, 0, 0)
whiteColour = pygame.Color(255, 255, 255)
greyColour = pygame.Color(150, 150, 150)
bobPosition = [300,70]
direction = 'right'
changeDirection = direction
pygame.draw.rect(playSurface,redColour,Rect(bobPosition[0], bobPosition[1], 40, 40))
pygame.display.flip()

length = 100
obstPosition = [100,475]
while True:
    if obstPosition[1] < 25:
        x = random.randint(10,505)
        obstPosition = [x,475]
        length += random.randint(1,5)
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
        elif event.type == KEYDOWN:
            if event.key == K_RIGHT or event.key == ord('d'):
                changeDirection = 'right'
            if event.key == K_LEFT or event.key == ord('a'):
                changeDirection = 'left'
            if event.key == K_ESCAPE:
                pygame.event.post(pygame.event.Event(QUIT))
    direction = changeDirection
    if direction == 'right':
        bobPosition[0] += 20
    if direction == 'left':
        bobPosition[0] -= 20
    playSurface.fill(blackColour)
    a = ['one','two','three']
    # Creating the obstacle
    pygame.draw.rect(playSurface,whiteColour,Rect(obstPosition[0], obstPosition[1], length, 20))
    obstPosition[1] -= 10
    # Creating "bob the block"
    pygame.draw.rect(playSurface,redColour,Rect(bobPosition[0], bobPosition[1], 25, 25))
    pygame.display.flip()
    if bobPosition[0] > 620 or bobPosition[0] < 0:
        gameOver()
    if bobPosition[1] > 460 or bobPosition[1] < 0:
        gameOver()

    fpsClock.tick(19)

1 个答案:

答案 0 :(得分:2)

将两个Rect存储为变量,并使用pygame.Rect.colliderect()来测试它们是否重叠。

例如:

rect1 = Rect(0,0,100,100)
rect2 = Rect(90,90,100,100)

collideTest = rect1.colliderect(rect2)