python - 没有类的 Pygame 碰撞

标签 python python-2.7 pygame

我是一个相对较新的 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

最佳答案

pygame.sprite.colliderect 方法用于检查 Sprite 之间的碰撞,而不是您正在使用的矩形之间的碰撞。 Sprite 是 pygame.sprite.Sprite 类的实例。您试图检测矩形之间的碰撞,矩形有自己的碰撞检测方法:b1.colliderect(b2)。矩形不是 Sprite , Sprite 也不是矩形。

关于python - 没有类的 Pygame 碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33070151/

相关文章:

python - 为什么只读属性是可写的?

python-3.x - 我的 Python 游戏敌人正在循环移动

python - Discord.py - 检查用户是否具有执行命令的特定角色

python - 在 Python 中分析内存分配(支持 Numpy 数组)

python - 如何构建 python 函数结果的通用总和

python - 导入错误:没有名为 pynotify 的模块。安装模块时

image - 类似于 Haskell 的 Pygame?

pygame - 无法在 pygame 上移动玩家

Python-tkinter : Opening and closing dialog windows

python - 在 Python 中隐藏代码或阻止代码编辑