所以我一直在使用 Pygame 制作一个小游戏。这只是一个测试,我正在努力让玩家站在草地上。但是,当我运行它时,我得到 AttributeError:“pygame.Rect”对象没有属性“rect”。
怎么了?我看过其他论坛,但似乎没有人有相同类型的脚本。
import os
WIDTH, HEIGHT = 900, 500
WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("cul game")
FPS = 60
PERSON_IMAGE = pygame.image.load(os.path.join("Character.png"))
PERSON = pygame.transform.scale(PERSON_IMAGE, (100, 100))
GRASS_IMAGE = pygame.image.load(os.path.join("Grass.png"))
GRASS = pygame.transform.scale(GRASS_IMAGE, (80, 80))
SPEED = 5
def collision(person, grass):
collisions = pygame.sprite.collide_rect(person, grass)
def draw_window(person, grass):
WINDOW.fill((30, 30, 30))
WINDOW.blit(PERSON, (person.x, person.y))
WINDOW.blit(GRASS, (grass.x, grass.y))
pygame.display.update()
def main():
person = pygame.Rect(-8, 300, 100, 100)
grass = pygame.Rect(-8, 429, 80, 80)
clock = pygame.time.Clock()
run = True
while run:
collision(person, grass)
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_a]:
person.x -= SPEED
if keys_pressed[pygame.K_d]:
person.x += SPEED
if keys_pressed[pygame.K_w]:
person.y -= SPEED
else:
person.y += SPEED
draw_window(person, grass)
pygame.quit()
if __name__ == "__main__":```
main()
person
和 grass
是 pygame.Rect
对象。因此,您必须使用 pygame.Rect.colliderect
,而不是 pygame.sprite.collide_rect
。 pygame.sprite.collide_rect
,适用于 pygame.sprite.Sprite
对象。
colliderect
是一种方法。因此:
collisions = pygame.sprite.collide_rect(person, grass)
collisions = pygame.Rect.colliderect(person, grass)
或
collisions = person.colliderect(grass)