我遇到了问题,因此将变量all_sprites调用为pygame.Group()不会返回任何值,我无法解决原因。
class game:
def __init__(self):
pg.init()
self.screen = pg.display.set_mode((screenwidth, screenheight))
pg.display.set_caption("Gammee")
self.clock = pg.time.Clock()
def run(self):
while True:
self.dt = self.clock.tick(FPS) / 1000
self.events()
self.update()
self.draw()
def new(self):
self.othersprites = pg.sprite.Group()
def draw(self):
self.screen.fill(BGCOLOR)
self.othersprites.draw(self.screen)
pg.display.flip()
def quit(self):
pg.quit()
sys.exit()
def update(self):
self.othersprites.update()
def events(self):
for event in pg.event.get():
if event.type == pg.QUIT:
self.quit()
g = game()
while True:
g.new()
g.run()
这是游戏的代码
class Player(pg.sprite.Sprite):
def __init__(self, game, x, y):
self.groups = game.all_sprites
pg.sprite.Sprite.__init__(self, self.groups)
self.game = game
self.image = pg.Surface((30, 30), SRCALPHA)
self.image.fill(YELLOW)
self.rect = self.image.get_rect()
self.vx, self.vy = 0, 0
self.x = x
self.y = y
def get_keys(self):
keys = pg.key.get_pressed()
if keys[pg.K_LEFT] or keys[pg.K_a]:
self.vx = -PLAYER_SPEED
if keys[pg.K_RIGHT] or keys[pg.K_d]:
self.vx = PLAYER_SPEED
if keys[pg.K_UP] or keys[pg.K_w]:
self.vy = -PLAYER_SPEED
if keys[pg.K_DOWN] or keys[pg.K_s]:
self.vy = PLAYER_SPEED
if len(keys) != 0:
self.vx *= 0.9
self.vy *= 0.9
def update(self):
self.get_keys()
self.x += self.vx * self.game.dt
self.y += self.vy * self.game.dt
self.rect.x = self.x
self.rect.y = self.y
然而,没有任何东西被吸引到碎片上。我还测试了
for sprite in self.all_sprites:
print(sprite)
用于在精灵上输出信息,但现在什么也没做,
关于我做错了什么的任何想法?
答案 0 :(得分:0)
您必须在Player
类的new
方法中创建game
的实例。此外,精灵组在othersprites
类中称为game
,在all_sprites
类中称为Player
,但名称必须匹配。
class game:
def new(self):
self.othersprites = pg.sprite.Group()
# This is how you create an instance/object.
self.player = Player(self, 200, 300)
class Player(pg.sprite.Sprite):
def __init__(self, game, x, y):
self.groups = game.othersprites
我认为在新方法中将self.player
精灵添加到self.othersprites
而不是将整个game
实例传递给播放器会更好更简单。
class game:
def new(self):
self.othersprites = pg.sprite.Group()
self.player = Player(200, 300)
self.othersprites.add(self.player)