-2

I want to make a game where the player clicks on ducks using the pygame module in Python. I want to have 15 ducks, but I don't want to copy code for instantiating a duck and assigning it to a variable 15 times. My current code is below, and "eend" is the name I'm using for ducks:

eend = Actor('eend')
eend._surf = pygame.transform.scale(eend._surf, (50, 50))
eend.pos = 425, 300

eend1 = Actor('eend')
eend1._surf = pygame.transform.scale(eend1._surf, (50, 50))
eend1.pos = 425, 300

eend2 = Actor('eend')
eend2._surf = pygame.transform.scale(eend2._surf, (50, 50))
eend2.pos = 425, 300

eend3 = Actor('eend')
eend3._surf = pygame.transform.scale(eend3._surf, (50, 50))
eend3.pos = 425, 300

eend4 = Actor('eend')
eend4._surf = pygame.transform.scale(eend4._surf, (50, 50))
eend4.pos = 425, 300

eend5 = Actor('eend')
eend5._surf = pygame.transform.scale(eend5._surf, (50, 50))
eend5.pos = 425, 300

eend6 = Actor('eend')
eend6._surf = pygame.transform.scale(eend6._surf, (50, 50))
eend6.pos = 425, 300

eend7 = Actor('eend')
eend7._surf = pygame.transform.scale(eend7._surf, (50, 50))
eend7.pos = 425, 300

eend8 = Actor('eend')
eend8._surf = pygame.transform.scale(eend8._surf, (50, 50))
eend8.pos = 425, 300

eend9 = Actor('eend')
eend9._surf = pygame.transform.scale(eend9._surf, (50, 50))
eend9.pos = 425, 300

eend10 = Actor('eend')
eend10._surf = pygame.transform.scale(eend10._surf, (50, 50))
eend10.pos = 425, 300

eend11 = Actor('eend')
eend11._surf = pygame.transform.scale(eend11._surf, (50, 50))
eend11.pos = 425, 300

eend12 = Actor('eend')
eend12._surf = pygame.transform.scale(eend12._surf, (50, 50))
eend12.pos = 425, 300

eend13 = Actor('eend')
eend13._surf = pygame.transform.scale(eend13._surf, (50, 50))
eend13.pos = 425, 300

eend14 = Actor('eend')
eend14._surf = pygame.transform.scale(eend14._surf, (50, 50))
eend14.pos = 425, 300

What is a good way to create multiple instances of the class Actor without repeating the code 15 times?

Almog-at-Nailo
  • 1,152
  • 1
  • 4
  • 20
ibon
  • 1
  • 1

1 Answers1

1

You can create a function that creates ducks for you, and then create a list of ducks (instead of keeping them as separate variable names).

def create_duck(name='eend', scale=(50, 50), pos=(425, 300)):
    eend = Actor(name)
    eend._surf = pygame.transform.scale(eend8._surf, scale)
    eend.pos = pos
    return eend

eends = []
for i in range(14):
    eends.append(create_duck())

You can also have this function as a class method in your Actor class

Almog-at-Nailo
  • 1,152
  • 1
  • 4
  • 20
  • its nice but then i get this: Traceback (most recent call last): File "D:\python programs\eendjes vangen\eend.py", line 15, in eend.append(create_duck()) File "D:\python programs\eendjes vangen\eend.py", line 8, in create_duck eend = Actor(eend) UnboundLocalError: local variable 'eend' referenced before assignment – ibon Sep 17 '21 at 16:06
  • @ibon `eend = Actor(eend)` should be `eend = Actor(name)` – Almog-at-Nailo Sep 19 '21 at 08:00