Call a class from list

Viewed 49

I have 3 classes that look pretty much like this. just different names:

class CrossPipe(BasePipe):
    def __init__(self, position):
        BasePipe.__init__(self, position)
        self.current_pos_X = 0
        self.current_pos_y = 0
        self.flow_rect = Rect(0,0,settings.FLOW_WIDTH, 0)
        self.flow_rect.left = (settings.TUBE_SIZE / 2) - (settings.FLOW_WIDTH / 2)
        
    def update(self):
        BasePipe.update(self)
        if self.current_pos_y < settings.TUBE_SIZE:
            self.current_pos_y += 1
        self.flow_rect.bottom = self.current_pos_y
        pygame.draw.rect(self.image, settings.FLOW_COLOR, self.flow_rect, 1)

Each of the classes is a block for a game. The blocks go randomly in a list 4 at a time.

pipes = (StraightPipe, BentPipe, CrossPipe)
coming_pipes = []
done = 0
while done != 4:
    coming_pipes.append(random.choice(pipes).__name__)
    done += 1

This Makes a list that looks like this:

['BentPipe', 'CrossPipe', 'BentPipe', 'StraightPipe']

The 4 blocks in the list need show up on the screen, but in order to draw them on the screen i have to be able to call them from the list with placed.add(coming_pipes[0]((-2,0))) but since its a list of strings it gives placed.add("BentPipe"((-2,0))) which cant be called.

So, how can i call a class from a list, or add the classes to the list without it being a string?

I dont have much coding knowledge btw.

1 Answers

Don't put the names of the classes in the list; put the classes themselves.

pipes = (StraightPipe, BentPipe, CrossPipe)
coming_pipes = []
done = 0
while done != 4:
    coming_pipes.append(random.choice(pipes))
    done += 1

or more simply

coming_pipes = random.choices(pipes, k=4)
Related