元组没有属性“colliderect”?

问题描述 投票:0回答:1

所以我正在为学校评估制作一个游戏,其中乌龟必须到达水中。之前,我在测试游戏时,乌龟是一个矩形。但现在我希望乌龟实际上是一只乌龟,我是否合并了我制作的图像。我使用了

get_rect()
,但现在它说 Tuple 没有属性“colliderect”。我能做些什么?这是我当前的代码(相关部分):

#cross the sea
import pygame

pygame.init()

#set screen
SCREEN_HEIGHT = 800
SCREEN_WIDTH = 600

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

#sprite dimensions
goal_boundary1 = pygame.Rect((275, 200, 50, 50))
goal_boundary2 = pygame.Rect((275, 100, 50, 50))
goal_boundary3 = pygame.Rect((325, 150, 50, 50))
goal_boundary4 = pygame.Rect((225, 150, 50, 50))
goal = pygame.Rect((275, 150, 50, 50))
player = pygame.image.load('turtle1.png')
screen.blit(player, (275, 650))
wall1 = pygame.Rect((-25, 300, 400, 50))
wall2 = pygame.Rect((225, 500, 400, 50))
left_boundary = pygame.Rect((-50, 0, 50, 800))
right_boundary = pygame.Rect((600, 0, 50, 800))
top_boundary = pygame.Rect((0, -50, 600, 50))
bottom_boundary = pygame.Rect((0, 800, 600, 50))
player_rect = pygame.Surface.get_rect(player)
player_rect = (275, 650)
run = True
while run:
    
    screen.fill((0, 0, 0))
    
    pygame.draw.rect(screen, (0, 255, 0), wall1)
    pygame.draw.rect(screen, (0, 255, 0), wall2)
    pygame.draw.rect(screen, (255, 255, 0), left_boundary)
    pygame.draw.rect(screen, (255, 255, 0), right_boundary)
    pygame.draw.rect(screen, (255, 255, 0), top_boundary)
    pygame.draw.rect(screen, (255, 255, 0), bottom_boundary)
    pygame.draw.rect(screen, (0, 0, 255), goal)


    #controls
    key = pygame.key.get_pressed()
    if key[pygame.K_a] == True:
        player_rect.move_ip(-1, 0)
    elif key[pygame.K_d] == True:
        player_rect.move_ip(1, 0)
    elif key[pygame.K_s] == True:
        player_rect.move_ip(0, 1)   
    elif key[pygame.K_w] == True:
        player_rect.move_ip(0, -1) 
    
    #wall collisions
    if player_rect.colliderect(wall1):
        if key[pygame.K_a] == True:
            player_rect.move_ip(10, 0)
        elif key[pygame.K_d] == True:
            player_rect.move_ip(-10, 0)
        elif key[pygame.K_s] == True:
            player_rect.move_ip(0, -10)
        elif key[pygame.K_w] == True:
            player_rect.move_ip(0, 10) 

我期望玩家具有与矩形相同的全部功能,但我遇到了这个错误。

pygame tuples pygame-surface
1个回答
0
投票

您的代码的问题在于:

player_rect = (275, 650)

您为

player_rect
分配了元组类型,这会覆盖
get_rect()
返回的 recangle 对象,tuple 没有名为
colliderect
的属性,而 recangle 有。 要解决此问题,您需要使用
player_rect.topleft
来设置player_rect 的位置而不是覆盖它。 例如,您可以将行代码更改为:

player_rect = player.get_rect(topleft=(275, 650))  # Initial position

玩家对象与线上的同一个玩家:

player = pygame.image.load('turtle1.png')
© www.soinside.com 2019 - 2024. All rights reserved.