python - pygame中Rect类的属性错误
问题描述
我刚从 pygame 和 python 开始,所以没有判断力(谢谢:)),但我一直试图用它colliderect()
来检查两个rect
(蛇,食物;我认为)的碰撞。我不断收到此错误。AttributeError:'Food'对象没有属性'colliderect'我做错了什么?
# main function
def main():
clock = pygame.time.Clock()
FPS = 17
run = True
snake = Snake(random.randint(0, 400), random.randint(0, 400), 10, 10)
food = Food(random.randint(0, 400), random.randint(0, 400), 10, 10)
snakeVelocity_X = 0
snakeVelocity_Y = 0
lost = False
# snake object
# Rect object: Rect(x, y, width, height)
class Snake():
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def draw(self, gameScreen):
pygame.draw.rect(gameScreen, colors.BLACK, (self.x, self.y, self.width, self.height))
# def get_head_position(self):
# return self.x, self.y, self.width, self.height
# food object
class Food():
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.collide = False
def draw(self, gameScreen):
pygame.draw.rect(gameScreen, colors.YELLOW, (self.x, self.y, self.width, self.height))
# check for collision
if food.colliderect(snake):
print("collision")
以上是我认为足以表达我的观点的代码。
附言。我也是stackoverflow的新手,任何做/不做的事情。
解决方案
colliderect
是一种方法pygame.Rect
。然而Food
不是一个pygame.Rect
对象。
删除 attributes x
、y
和width
rect`height, but add a
属性:
class Food():
def __init__(self, x, y, width, height):
self.rect = pygame.Rect(x, y, width, height)
self.collide = False
def draw(self, gameScreen):
pygame.draw.rect(gameScreen, colors.YELLOW, self.rect)
现在您可以使用该colliderect
方法food.rect
:
if food.rect.colliderect(snake):
print("collision")
推荐阅读
- ios - react-native pjsip 模块 - iOS 背景没有接收
- spotify-docker-client - 如何将卷挂载到容器?
- sas - SAS:使用索引列作为提示的哈希表查找
- css - 仅使用 CSS 从中心旋转三角形图像?
- azure - 在 Azure AD Enterprise 应用程序中跳过 Home Realm Discovery Page 或 Microsoft 登录页面
- javascript - 函数调用内的javascript内联注释
- javascript - 使用最新 jQuery 的视差滚动不起作用
- r - 为 mlogit 设置 data.frame - 错误消息:`row.names<-.data.frame`(`*tmp*`, value = paste(chid, alt, sep = ".")) 中的错误:
- java - 如何解决此问题 (.getDownloadUrl()) 未出现在新版本的 Firebase 数据库中
- sql - 使用 laravel 在迁移中创建带有前缀和自动增量的值