我刚刚学会了如何在 pygame 中对内容进行分组,但是当我尝试使用它来绘制精灵时,它说:“ExternalError:TypeError:无法读取第 32 行未定义的属性 'left'”
这是我的代码:
import pygame
from pygame import *
screen = pygame.display.set_mode((600, 600))
blocks = pygame.sprite.Group()
class Block():
def __init__(self, x, y, w, h, typ):
super().__init__()
self.x = x
self.y = y
self.w = w
self.h = h
self.typ = typ
def draw(self):
pygame.draw.rect(screen, (0, 0, 0), (self.x, self.y, self.w, self.h))
class Player():
def __init__(self, x, y):
super().__init__()
self.x = x
self.y = y
self.accX = 0
self.accY = 0
def draw(self):
pygame.draw.rect(screen, (0, 0, 0), (self.x, self.y, 20, 20))
player = Player(0, 0)
while True:
Blocks = Block(0, 0, 100, 50, 1)
blocks.add(Blocks)
blocks.draw(screen)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
pygame.display.update()
答案 0 :(得分:0)
pygame.sprite.Group.draw()
和 pygame.sprite.Group.update()
是由 pygame.sprite.Group
提供的方法。
前者将 委托给包含的 pygame.sprite.Sprite
s 的 update
方法 - 您必须实现该方法。见pygame.sprite.Group.update()
:
对组中的所有 Sprite 调用 update()
方法 [...]
后者使用包含的 image
的 rect
和 pygame.sprite.Sprite
属性来绘制对象 - 您必须确保 pygame.sprite.Sprite
具有所需的属性。见pygame.sprite.Group.draw()
:
将包含的精灵绘制到 Surface 参数。这对源表面使用 Sprite.image
属性和 Sprite.rect
。 [...]
这意味着 Block
和 Player
必须派生自 pygame.sprite.Sprite
,并且必须具有属性 rect
和 image
。将 Block
和 Player
实例添加到 Group
并使用 darw()
方法绘制它们。
完整示例:
import pygame
from pygame import *
screen = pygame.display.set_mode((600, 600))
class Block(pygame.sprite.Sprite):
def __init__(self, x, y, w, h, typ):
super().__init__()
self.image = pygame.Surface((w, h))
self.image.fill((127, 127, 127))
self.rect = self.image.get_rect(topleft = (x, y))
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface((20, 20))
self.image.fill((255, 255, 0))
self.rect = self.image.get_rect(topleft = (x, y))
blocks = pygame.sprite.Group()
objects = pygame.sprite.Group()
block = Block(0, 0, 100, 50, 1)
blocks.add(block)
player = Player(0, 0)
objects.add(player)
clock = pygame.time.Clock()
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
screen.fill((0, 0, 0))
blocks.draw(screen)
objects.draw(screen)
pygame.display.update()
pygame.quit()