我是一个相对较新的python开发人员,我偶然发现了一个问题。我无法使用pygame.sprite.collide_rect()函数,我无法在网上找到任何解决方案。这是我的代码:
import sys
import pygame
pygame.init()
gameDisplay = pygame.display.set_mode((600,600))
pygame.display.set_caption('Doge Adventures')
gameexit = False
white = (255,255,255)
black = (0,0,0)
move_x = 300
move_y = 300
def checkCollision(sprite1, sprite2):
col = pygame.sprite.collide_rect(sprite1,sprite2)
if col == True:
sys.exit()
while not gameexit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameexit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
move_x -= 15
elif event.key == pygame.K_RIGHT:
move_x += 15
elif event.key == pygame.K_UP:
move_y -= 15
elif event.key == pygame.K_DOWN:
move_y += 15
gameDisplay.fill(white)
b1 = pygame.draw.rect(gameDisplay, black, [move_x, move_y, 40, 40])
b2 = pygame.draw.rect(gameDisplay, black, [450 , 450, 50, 50])
b1,b2
checkCollision(b1,b2)
pygame.QUIT()
quit()
我得到的错误是:
Traceback (most recent call last):
File "C:\Users\DEREK\My Documents\LiClipse Workspace\Doge Adventures\Game.py", line 45, in <module>
checkCollision(b1,b2)
File "C:\Users\DEREK\My Documents\LiClipse Workspace\Doge Adventures\Game.py", line 19, in checkCollision
col = pygame.sprite.collide_rect(sprite1,sprite2)
File "C:\Python26\lib\site-packages\pygame\sprite.py", line 1147, in collide_rect
return left.rect.colliderect(right.rect)
AttributeError: 'pygame.Rect' object has no attribute 'rect'
顺便说一下,我正在使用python 2.7
答案 0 :(得分:1)
pygame.sprite.colliderect
方法用于检查精灵之间的碰撞,而不是正在使用的矩形。精灵是pygame.sprite.Sprite
类的实例。你试图检测的是矩形之间的碰撞,它们有自己的碰撞检测方法:b1.colliderect(b2)
。矩形不是精灵,精灵不是矩形。