【问题标题】:Rect error in Python 3.6.2, Pygame 1.9.3Python 3.6.2、Pygame 1.9.3 中的 Rect 错误
【发布时间】:2017-09-01 14:11:39
【问题描述】:

我最近一直在学习 python,我刚刚发现了 sprites。它们看起来真的很有用,我一直在尝试制作一个游戏,你必须吃掉所有的红苹果(健康),而不是蓝苹果(发霉)。当我尝试运行它时出现错误,它说:

   line 32, in <module>
   apples.rect.y = random.randrange(displayHeight - 20)
   AttributeError: type object 'apples' has no attribute 'rect'

对不起,如果我犯了一个非常愚蠢的错误,但我一直在其他地方寻找答案,但我找不到。这是我的整个主要代码:

import pygame
import random

pygame.init()

displayWidth = 800
displayHeight = 600

black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)

gameDisplay = pygame.display.set_mode((displayWidth, displayHeight))
gameCaption = pygame.display.set_caption("Eat The Apples")
gameClock = pygame.time.Clock()

class apples(pygame.sprite.Sprite):
    def __init__(self, colour, width, height):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface([20, 10])
        self.image.fill(red)
        self.rect = self.image.get_rect()

applesList = pygame.sprite.Group()
allSpriteList = pygame.sprite.Group()

for i in range(50):
    apple = apples(red, 20 , 20)

    apples.rect.y = random.randrange(displayHeight - 20)
    apples.rect.x = random.randrange(displayWidth - 20)

    applesList.add(apple)
    allSpriteList.add(apple)

player = apples(green, 20, 20)

def gameLoop():

    gameExit = False

    while not gameExit:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gameExit = True

        pygame.display.update()
        gameClock.tick(60)

gameLoop()
pygame.quit()
quit()

感谢您的阅读,期待您的回复! (P.S. 如果您想知道,这段代码还没有完全完成)

【问题讨论】:

    标签: python-3.x pygame rect


    【解决方案1】:

    您试图在此处更改类的 rect 属性而不是实例的矩形,并且由于该类没有矩形,因此引发了 AttributeError

    apples.rect.y = random.randrange(displayHeight - 20)
    apples.rect.x = random.randrange(displayWidth - 20)
    

    只需将apples 更改为apple(实例),它应该可以正常工作。

    apple.rect.y = random.randrange(displayHeight - 20)
    apple.rect.x = random.randrange(displayWidth - 20)
    

    【讨论】:

    • PEP 8 建议对类使用驼峰命名,例如class MyClassName:,小写代表变量和函数。
    • 感谢您的帮助,我也想知道如何显示这些精灵。可能有一个非常简单的答案,但请耐心等待我是初学者。
    • 看看chapter 13 of Program Arcade Games。它向您展示了如何使用精灵和精灵组。您只需将所有精灵放入一个组(例如命名为all_sprites),然后在主循环中调用all_sprites.update()all_sprites.draw(gameDisplay) 来更新所有精灵并绘制它们。
    【解决方案2】:

    是的,就像 skrx 说的那样。你只需要挑出一个。 苹果中的苹果:

    应该可以。

    【讨论】:

      猜你喜欢
      • 2015-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-21
      • 1970-01-01
      • 2015-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多