我正在尝试运行本教程https://opensource.com/article/17/12/game-python-add-a-player中的以下pytho pygame代码。
纠正了我在此问题'Player' object has no attribute 'rect上发布的缩进之后,我尝试运行下面的python代码,然后运行名为images
的本地文件夹中的文件树,如下所示。
但是我看不到游戏中的hero.png。我也尝试Pygame player sprite not appearing。
文件夹图片:
stage.png:https://imgur.com/YyiEJ0q hero.png:https://opengameart.org/sites/default/files/spellun-sprite.png
我的代码:
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):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.images = []
img = pygame.image.load(os.path.join('images','hero.png')).convert()
self.images.append(img)
self.image = self.images[0]
self.rect.x = 40
self.rect.y = 30
#cria a classe para o player
'''
Objects
'''
# put Python classes and functions here
'''
Setup
'''
worldx = 260
worldy = 220
fps = 40 # frame rate
ani = 4 # animation cycles
clock = pygame.time.Clock()
pygame.init()
#BUG REMOVIDO: BUG É ".convert()" da linha "backdrop = pygame.image.load(os.path.join('images','stage.png').convert())"
world = pygame.display.set_mode([worldx,worldy])
backdrop = pygame.image.load(os.path.join('images','stage.png'))
backdropbox = world.get_rect()
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)
# put game loop here
pygame.display.flip()
clock.tick(fps)
答案 0 :(得分:1)
您必须将属性.rect
添加到Player
:
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.images = []
img = pygame.image.load(os.path.join('images','hero.png')).convert()
self.images.append(img)
self.image = self.images[0]
self.rect = self.image.get_rect() # <----
self.rect.x = 40
self.rect.y = 30
创建一个Player实例。创建pygame.sprite.Group
和add
palyer
:
player = Player()
all_sprites = pygame.sprite.Group()
all_sprites.add(player)
使用draw()
绘制组中的所有精灵。 draw
利用Sprite的image
和rect
属性来绘制组中的所有Sprite:
all_sprites.draw(world)
尊重Indentation:
while main == True:
# handle events
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
# draw background
world.blit(backdrop, backdropbox)
# draw scene
all_sprites.draw(world)
# update display
pygame.display.flip()
clock.tick(fps)