I have recently been learning python and I just found out about sprites. They seem really useful and I have been trying to make a game where you have to eat all the red apples (healthy), and not the blue apples (mouldy). An error occurred when I tried to run it and it said:
line 32, in <module>
apples.rect.y = random.randrange(displayHeight - 20)
AttributeError: type object 'apples' has no attribute 'rect'
Sorry if I have made a really nooby error but I have been looking for an answer elsewhere and I couldn't find one. Here is my entire main code:
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()
Thank you for reading and I look forward to a response! (P.S. This code isn't completely finished if you were wondering)
You're trying to change the rect
attribute of the class here not the rect of the instance, and since the class doesn't have a rect, the AttributeError
is raised.
apples.rect.y = random.randrange(displayHeight - 20)
apples.rect.x = random.randrange(displayWidth - 20)
Just change apples
to apple
(the instance) and it should work correctly.
apple.rect.y = random.randrange(displayHeight - 20)
apple.rect.x = random.randrange(displayWidth - 20)