0

I am having some trouble with my code. I was wondering how to call a specific class. Here is my code:

choices = [Enemy, Enemy2]

def create_enemies(rows, columns):
    enemy_x = x
    enemy_y = y
    for rows in range(0, rows):
        for columns in range(0, columns):
            rand_num = random.randint(1, 3)
            if rand_num == 1:
                enemy = random.choice(choices)(enemy_x, enemy_y)
                enemy_sprites.add(enemy)
            enemy_x += spacing_x
        enemy_y += spacing_y
        enemy_x = x

and then:

for enemy in enemy_sprites:
    enemy.update()
    if enemy.rect.colliderect(player):
        health -= 10
        enemy_sprites.remove(enemy)

I have an Enemy and an Enemy2 class, but they are both defined as enemy in my create_enemies function. I was wondering how to get the specific enemy class to collide with the player instead of just checking both at the same time. I want to use this for taking different amounts of health. Any help is greatly appreciated!

kdl
  • 55
  • 6
  • 1
    You haven't defined any classes in this code. – Błotosmętek Jul 02 '17 at 18:09
  • I defined the class here: enemy = random.choice(choices)(enemy_x, enemy_y) – kdl Jul 02 '17 at 18:31
  • 1
    if the health decreases depending on the enemy, why not create an attribute `damage` in your enemies classes ? then you only have to call enemy.damage instead of hardcoding the health number ? – PRMoureu Jul 02 '17 at 18:48
  • Ah yes, thank you sometimes I get so focused on one way to do it while there is a much easier way. – kdl Jul 02 '17 at 18:53
  • `enemy = random.choice(choices)(enemy_x, enemy_y)` does not define a class, as far as I can tell. It looks like it may instantiate an object though. – juanpa.arrivillaga Jul 02 '17 at 19:24
  • The term `class` has a specific meaning in object-oriented programming. Please read the Python manual. – Błotosmętek Jul 02 '17 at 19:30
  • 1
    @Błotosmętek the classes are `Enemy` and `Enemy2`. The list `choices` contains an object of each of those classes. Hence calling ` random.choice(choices)(enemy_x, enemy_y)` will randomly create an instance of `Enemy` or `Enemy2`, passing `enemy_x` and `enemy_y` to their `__init__` functions. – sloth Jul 04 '17 at 07:27

0 Answers0