为什么我得到模块“Pygame.surface”没有属性“get_rect”

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

所以我有一个关于我正在制作的策略游戏的课程,我正在尝试将我的 PNG 切换为正常的 pygame 方块。但是我收到错误 -> AttributeError: module 'pygame.surface' has no attribute 'get_rect'

(完全错误)->

File "/Users/wallera/PycharmProjects/--------/main.py", line 20, in <module>
red_region1 = Region(300, 0, "red")
              ^^^^^^^^^^^^^^^^^^^^^
File "/Users/wallera/PycharmProjects/------/Region.py", line 21, in __init__
self.rect = self.image_rect.get_rect()
            ^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'pygame.surface' has no attribute 'get_rect'

这就是我目前的课程 ->

class Region:
    def __init__(self, x, y, colour):
        self.x = x
        self.y = y
        self.colour = colour

        # Load the correct image file for the colour of this region
        if self.colour == "red":
            self.image = pygame.surface
        elif self.colour == "blue":
            self.image = pygame.image.load("/Users/wallera/PycharmProjects/MAJORPROJECT2/Assets/square_blue_region1.png")
            pass
        else:
            print(f"Unknown colour: {self.colour}")

        # Position the image correctly
        self.rect = self.image.get_rect()
        self.rect.topright = (self.x, self.y)

    def draw(self, screen):
        screen.blit(self.image, (self.rect.x, self.rect.y))

如果需要,这是游戏的主要代码:

pygame.init()
screen = pygame.display.set_mode((1000, 700))  # The display window

pygame.display.set_caption('Turn Based Strategy Game')  # Name is subject to change
framerate = pygame.time.Clock()  # setting the fps to 60, so it stays consistent and no fluctuations to make it stable



bottom_menu = pygame.Surface((1000, 150))
next_turn_holder = pygame.Surface((250, 225))

bottom_menu.fill('Grey')
next_turn_holder.fill('Grey')

red_region1 = Region(300, 0, "red")
blue_region1 = Region(600, 0, "blue")


while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()  # Exit the game

        if event.type == pygame.KEYDOWN and event.key == pygame.K_TAB:
            pygame.display.toggle_fullscreen()

    screen.fill('lightblue')
    red_region1.draw(screen)
    blue_region1.draw(screen)

    pygame.display.update()
    #framerate.tick(60)  # maximum framerate

我不确定为什么它不起作用,并且希望得到任何帮助,我认为这可能是因为表面无法分配一个矩形(我在那里有图像,因为我试图从 PNG 切换)对齐得很好,我需要完美的东西)

这是我第一次使用 pygame,所以我不太习惯它的文档(我相信这可以使用一些改进)

python pygame
1个回答
0
投票

如果你想创建一个颜色统一的图像,你必须创建一个

pygame.Surface
对象并用颜色填充它:

self.image = pygame.surface

self.image = pygame.Surface((height, width), pygame.SRCALPHA)
self.image.fill(colour)
© www.soinside.com 2019 - 2024. All rights reserved.