Unable to change the x coordinate of Rect object for each item in a list

Question:

I am currently trying to draw a pipe for each item in a list so that I have multiple objects on the screen.

    def draw(self):
        for i in pipes:
            self.top_rect = pygame.draw.rect(
                DISPLAYSURF,YELLOW,((self.__x + (i * 100)), ((self.__y - self.__h) - 185), self.__w, self.__h),
            )

However when I try to make it so the x coordinate changes for each pipe, I get, "unsupported operand type(s) for *: ‘Pipe’ and ‘int’s" (the class is called Pipe). This issue does not occur if I change it from pipes to range(pipes). Am I missing something obvious?

Asked By: Apple_Retainer

||

Answers:

So currently, your for loop is looping through instances of the class Pipe, what you need to do instead is this:

for j, i in enumerate(pipes):
    self.top_rect = pygame.draw.rect(
                DISPLAYSURF,YELLOW,((self.__x + (j * 100)), ((self.__y - self.__h) - 185), self.__w, self.__h),
            )

enumerate provides two values, the current iteration count and the value of the iteration, so here, j is the iteration count and i is the iterated value of the list pipes.

Notice I swapped out i for j in the draw call

Answered By: tygzy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.