我正在尝试使用正在开发的pygame为平台游戏创建块,但不知道该怎么做。我尝试这样做,以便您可以轻松地在关卡列表中写一个“ B”来创建一个块,并以此方式构建游戏的结构。因此,我基本上想知道的是,如何找到每个B:s的x和y坐标,并将它们放在列表中,然后将其显示在屏幕上。我已经让玩家按照自己的意愿进行工作,所以方块现在是主要缺少的部分。平台(aka块)的代码如下所示:
class Platform(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = Surface((25, 25))
self.image.fill(red)
self.rect = self.image.get_rect()
def update(self):
x = y = 0
platforms = []
level = [
"BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
"B B",
"B B",
"B BBBB B",
"B B",
"B BBBB B",
"B B",
"BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",]
for row in level:
for colum in row:
if colum == "B":
Block = x = y
platforms.append(Block)
all_sprites.add(Block)
x += 25
y += 25
上面显示的所有代码之后,我说:
platform = Platform()
all_sprites.add(platform)
#all_sprites是我为所有sprite组成的组
然后在游戏的主while循环中,我写道:
all_sprites.update()
任何帮助或其他想法将不胜感激。如果您与做过类似事情的人有任何链接,那也很好。
答案 0 :(得分:0)
这是创建平台的一种简单方法:我定义一个rects列表(在这种情况下,仅包含四个元素的元组),对其进行迭代以创建平台实例并将其添加到sprite组。
import pygame as pg
pg.init()
# Better create or load the images/surfaces before the game
# starts because that's more efficient.
PLATFORM_IMAGE = pg.Surface((50, 50))
PLATFORM_IMAGE.fill(pg.Color('dodgerblue1'))
class Platform(pg.sprite.Sprite):
def __init__(self, x, y, image):
super().__init__()
self.image = image
self.rect = self.image.get_rect(topleft=(x, y))
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
all_sprites = pg.sprite.Group()
platforms = pg.sprite.Group()
coords = [(100, 200), (150, 200), (350, 100)]
for x, y in coords:
# Pass the x- and y-coords and the surface.
platform = Platform(x, y, PLATFORM_IMAGE)
# Add the sprite to the corresponding groups.
all_sprites.add(platform)
platforms.add(platform)
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
all_sprites.update()
screen.fill((30, 30, 30))
all_sprites.draw(screen)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
main()
pg.quit()
如果要使用字符串列表作为级别,则可以使用两个for
循环和enumerate
函数:
level = [
"BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
"B B",
"B B",
"B BBBB B",
"B B",
"B BBBB B",
"B B",
"BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
]
all_sprites = pg.sprite.Group()
platforms = pg.sprite.Group()
width = PLATFORM_IMAGE.get_width()
for y, row in enumerate(level):
for x, item in enumerate(row):
if item == 'B':
platform = Platform(x*width, y*width, PLATFORM_IMAGE)
all_sprites.add(platform)
platforms.add(platform)