Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading