Home > Software design >  Unable to change the x coordinate of Rect object for each item in a list
Unable to change the x coordinate of Rect object for each item in a list

Time:12-22

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?

CodePudding user response:

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

  • Related