I currently try to create a game with pygame, after defining the sprite Enemy, Player, and Skill, I hope the function of the skill is that the Player shoots the skill to the nearest Enemy per second, how do I get the nearest Enemy position?
While I used for loop to display the Enemy sprite in range(8) randomly from the edge of the game screen, and after one Enemy gets killed, the new enemy will be displayed. But when I use for loop, how could I know which one is sprite[1] and which one is sprite[2] followingly? Is there any way to put the sprites I created in a list or something else? So as that I can analyze which one is the nearest and let the Skill track it and kill it.
The Enemy sprite class:
`
class Enemy(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.transform.scale(ayu_img, (64, 64)) # sprite elements
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect() # sprite location fixed
self.radius = 32
randomNum = random.randrange(1, 4) # Dice for 1 to 4 condition
if randomNum == 1:
self.rect.x = random.randrange(-40, -32)
self.rect.y = random.randrange(0, HEIGHT - self.rect.height)
elif randomNum == 2:
self.rect.x = random.randrange(WIDTH 32, WIDTH 40)
self.rect.y = random.randrange(0, HEIGHT - self.rect.height)
elif randomNum == 2:
self.rect.x = random.randrange(0, WIDTH - self.rect.width)
self.rect.y = random.randrange(-40, -32)
elif randomNum == 4:
self.rect.x = random.randrange(0, WIDTH - self.rect.width)
self.rect.y = random.randrange(HEIGHT 32, HEIGHT 40)
self.speedx = random.randrange(1, 2)
self.speedy = random.randrange(1, 2)
def update(self):
if self.rect.centerx > player.rect.centerx: # movement judge
self.rect.centerx -= self.speedx
else:
self.rect.centerx = self.speedx
if self.rect.centery > player.rect.centery:
self.rect.centery -= self.speedy
else:
self.rect.centery = self.speedy
`
The way I create enemy in game
`
for i in range(8):
enemy = Enemy() # create entity
all_sprites.add(enemy) # put into the sprite list
enemies.add(enemy) # put into the enemy list
`
is there any way to make enemy to enemy[ i ] for i in range(8)? or someway else? I am not sure if my idea is good or there is a simplified way to do it ...
CodePudding user response:
A pygame.sprite.Groups
can be iterated:
for sprite in all_sprites:
# [...]
of course you can enumerate
the sprites:
for i, sprite in enumerate(all_sprites):
# [...]
and you can get a list of Sprites with pygame.sprite.Group.sprites
:
sprite_list = all_sprites.sprites()
if len(sprite_list) > 0:
sprite_0 = sprite_list[0]
# [...]