简体   繁体   中英

my Rect stays for 1 frame created in 'for in' loop Pygame

The problem lies in the algorithm instead of Pygame. 'rows' is an array of pygame.rect()s. the rect created in the last line only stays for 1 frame. how would i go about fixing this problem?

sorry if its a shit question, i'm gracious for the help

for row in rows:
      moupos = pygame.mouse.get_pos()
      mouclick = pygame.mouse.get_pressed()
      if mouclick[0] == 1 and row.collidepoint(moupos):
          row = pygame.draw.rect(screen,green,row)

You need to somehow keep track of which rect you already clicked.

There are of course endless ways to do this. One way is to use a custom class instead of a simple Rect so we can easily keep track of the state of each "row".

Here's a simple example:

import pygame

class Row:
    def __init__(self, rect):
        self.rect = rect
        self.clicked = False

def main():
    pygame.init()
    quit = False
    screen = pygame.display.set_mode((230, 230))
    clock = pygame.time.Clock()

    rows = [
        Row(pygame.Rect(10, 10, 100, 100)),
        Row(pygame.Rect(10, 120, 100, 100)),
        Row(pygame.Rect(120, 10, 100, 100)),
        Row(pygame.Rect(120, 120, 100, 100))
    ]

    while not quit:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return 
            if event.type == pygame.MOUSEBUTTONDOWN:
                for row in (row for row in rows if row.rect.collidepoint(event.pos)):
                    row.clicked = True

        screen.fill(pygame.Color('grey12'))
        moupos = pygame.mouse.get_pos()
        for row in rows:
            if row.clicked:
                color = pygame.Color('orange')
            else:
                color = pygame.Color('green') if row.rect.collidepoint(moupos) else pygame.Color('dodgerblue')
            pygame.draw.rect(screen, color, row.rect)

        pygame.display.flip()
        clock.tick(60)

if __name__ == '__main__':
    main()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM