0

I have a problem with list

class Platform:
    countOfPlatforms = 10
    def __init__(self):
        self.PLATFORM_IMG = pygame.image.load('assets/platform.png')
        self.position = [[0, 0]]
    def width(self):
        return self.PLATFORM_IMG.get_width()
    def height(self):
        return self.PLATFORM_IMG.get_height()
    def setPos(self, x, y):
        self.position[0] = x
        self.position[1] = y
    def setPos(self, args):
        self.position = [args[0], args[1]]
    def pos(self):
        return [ self.position[0], self.position[1] ]
    def x(self):
        return self.pos()[0]
    def y(self):
        return self.pos()[1]
         
 
FPS = 60
fpsClock = pygame.time.Clock()
WIDTH = 400
HEIGHT = 533
MID_HEIGHT = 200
DISPLAYSURF = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
 
hero = player.Player()
platformObjects = [Platform()] * Platform.countOfPlatforms
platforms = [[0, 0]] * Platform.countOfPlatforms
 
for i in range(Platform.countOfPlatforms):
    randomX = random.randrange(0,WIDTH)
    randomY = random.randrange(0,HEIGHT)
    platformObjects[i].setPos([randomX, randomY])
    #platforms[i] = [randomX, randomY]
 
 
pygame.display.set_caption('Ice Tower')
 
def main():
    while True: # the main game loop        
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
 
        for i in range(Platform.countOfPlatforms):
            DISPLAYSURF.blit(platformObjects[i].PLATFORM_IMG, platformObjects[i].pos())
            #DISPLAYSURF.blit(platformObjects[i].PLATFORM_IMG, platforms[i])
         
        pygame.display.update()
        fpsClock.tick()

I'm trying to create a list with classes that have an item position, which later draws if I use the above code the result will be. bad result

but if it uncomments the code '#' then everything is OK

good result

In summary, if I use the code above, all values have the same position even though I checked with print() that the values are random, but if they enter the While True loop, suddenly all values are the same. I'm not a python expert and any help would be appreciated.

I dont know why this values are different because should be the same.

Best regards

1 Answers1

1

The following statement creates a Platform object, but a list of Platform.countOfPlatforms elements that all refer to the same single object:

platformObjects = [Platform()] * Platform.countOfPlatforms

You have to create the list with List Comprehensions. In this case, a new object is created for each item in the sequence:

platformObjects = [Platform() for _ in range(Platform.countOfPlatforms)]
Rabbid76
  • 202,892
  • 27
  • 131
  • 174