问题
I have been trying for a while to resolve the following error message: '' Player 'object has no attribute' rect '.
I have researched here in stack.overflow and see that it may be related to the type of declaration or indentation.
But I can't understand where the code fails.
The original code is from this tutorial: https://opensource.com/article/17/12/game-python-add-a-player
My code:
import pygame # load pygame keywords
import sys # let python use your file system
import os # help python identify your OS
'''
Create class for player
'''
class Player(pygame.sprite.Sprite):
'''
Spawn a player
'''
pygame.display.set_mode()
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.images = []
img = pygame.image.load(os.path.join('images','hero' + str(i) + '.png')).convert()
img.convert_alpha() # optimise alpha
img.set_colorkey(ALPHA) # set alpha
self.images.append(img)
self.image = self.images[0]
self.rect = self.image.get_rect()
'''
Objects
'''
# put Python classes and functions here
'''
Setup
'''
ALPHA = (0, 255, 0)
worldx = 960
worldy = 720
fps = 40 # frame rate
ani = 4 # animation cycles
clock = pygame.time.Clock()
pygame.init()
world = pygame.display.set_mode([worldx,worldy])
backdrop = pygame.image.load(os.path.join('images','stage.png'))
backdropbox = world.get_rect()
player = Player() # spawn player
player.rect.x = 0 # go to x
player.rect.y = 0 # go to y
player_list = pygame.sprite.Group()
player_list.add(player)
BLUE = (25,25,200)
BLACK = (23,23,23 )
WHITE = (254,254,254)
main = True
# put run-once code here
'''
Main Loop
'''
while main == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit(); sys.exit()
main = False
if event.type == pygame.KEYDOWN:
if event.key == ord('q'):
pygame.quit()
sys.exit()
main = False
world.blit(backdrop, backdropbox)
player_list.draw(world) # draw player
# put game loop here
pygame.display.flip()
clock.tick(fps)
来源:https://stackoverflow.com/questions/59700090/player-object-has-no-attribute-rect