我不能给你一个完整的答案,用你的游戏特定的代码,但是我可以给你一些提示,让整个事情变得更简单,这会让你更好地控制游戏中的所有元素。
首先,你应该有一个“容器”为你的精灵。你可以为每件事物配备一个,或者更好的是,以合理的方式分组。例如,你可能有环境精灵,敌人,盟友,平视显示器等。什么决定你如何将你的精灵分组,基本上是他们所做的:类似行为的精灵应该组合在一起。
你可以使用一个数组,但由于你使用的是pygame
,所以我建议使用pygame.sprite.Goup
- 这样可以实现像.update
和.draw
这样的方法,这将大大提高你的代码的可理解性,从而控制游戏。
你应该在每一帧都有一个“游戏循环”(尽管我猜你已经这么做了),这是所有事情发生的地方。喜欢的东西:
# This code is only intended as a generic example. It wouldn't work on it's
# own and has many placehoders, of course. But you can adapt your
# game to have this kind of structure.
# Game clock keeps frame rate steady
theClock = pygame.time.Clock()
# Sprite groups!
allsprites = pygame.sprite.Group()
environmentSprites = pygame.sprite.Group()
enemySprites = pygame.game.Group()
# Initially populate sprite groups here, e.g.
environmentSprites.add(rockSprite)
allsprites.add(rockSprite)
# ...
# Game loop
while True:
theClock.tick(max_fps)
# Add new enemies:
spawn_enemies(enemySprites, allSprites, player_score)
# Update all sprites
environmentSprites.update()
enemySprites.update()
playerSprite.update()
# ...and draw them
allSprites.draw(background)
window.blit(background)
pygame.display.flip()
这种方式可以让你的游戏循环短(如在没有太多的线条,最外部化的实际工作中,以函数和方法),因此有超过发生什么更多的控制。
实现你想要的东西现在多了,简单得多。你有一个单独的功能可以做到这一点,只有这一点,这意味着你可以专注于你想要敌人如何产生与player_score
相关的东西。把我的头顶部只是一个例子:
def spawn_enemies(enemyGroup, all, player_score):
# Calculate the number of enemies you want
num_enemies = player_score/100
for i in range(num_enemies):
# Create a new enemy sprite instance and
# set it's initial x and y positions
enemy = EnemyClass()
enemy.xpos = random.randint(displayWidth, displayWidth + 100)
enemy.ypos = random.randint(0, displayHeight)
enemy.velocity = (player_score/100) * base_velocity
# Add the sprite to the groups, so it'll automatically
# be updated and blitted in the main loop!
enemyGroup.add(enemy)
all.add(enemy)
,我建议你在pygame docs and tutorials的东西像pygame.sprite.Sprite
,pygame.sprite.Group
和pygame.time.Clock
阅读,如果你还没有准备好。我发现他们在开发我的游戏时非常有用。教程也给了游戏最佳结构的一个很好的概念。
希望这会有所帮助。
如果你让你精神振奋,就可以说列表中包含每个(x,y)的坐标,你可以先移动每个灵魂然后将它们移动,让你对自己有更多的控制权游戏。 – Simon