Deleting/Duplicating class 的一个实例,当有很多

Deleting/Duplicating an instance of a class when there are many

我正在尝试删除安全区外的点,但到目前为止,我找到的唯一解决方案是不绘制它们,这不是我想要的,因为使用这种方法它们仍然存在。有没有办法删除这个区域之外的特定点?还有一种方法可以创建实例的副本吗?

import pygame
import sys
import random
pygame.init()
win = pygame.display.set_mode((800,600))
pygame.display.set_caption("Simulation")

class Dot:
    def __init__(self):
        self.spawnX = random.randrange(0, 800)
        self.spawnY = random.randrange(0, 600)
        self.r = random.randrange(0, 256)
        self.g = random.randrange(0, 256)
        self.b = random.randrange(0, 256)

        self.vel = [None] * 0
        self.spd = random.random()
        self.vel.append(self.spd)
        self.vel.append(self.spd * -1)
        self.fertility = random.randrange(0, 3)

def safeZone():
        #Draws a top rectangle
    pygame.draw.rect(win, (50,205,50), (0, 0, 800, 100))
        
def drawdot(dot):
    width = 10
    height = 10
    pygame.draw.rect(win, (dot.r, dot.g, dot.b), (dot.spawnX, dot.spawnY, width, height))

def population(dots):
    for dot in dots:
        dot.spawnX += random.choice(dot.vel)
        dot.spawnY += random.choice(dot.vel)
        if dot.spawnX >= 800:
            dot.spawnX -= 5
        if dot.spawnY >= 600:
            dot.spawnY -= 5
        if dot.spawnX <= 0:
            dot.spawnX += 5
        if dot.spawnY <= 0:
            dot.spawnY += 5
        if dot.spawnX >= 0 and dot.spawnY >= 100:
            pass  #Here I want to delete the objects outside of this region
        drawdot(dot)

alldots = [Dot() for _ in range(1000)]

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    win.fill((255, 255, 255))
    safeZone() # Always draw dots after safe zone
    population(alldots)
    pygame.display.update()

“不绘制它们”只是意味着将它们从它们所在的容器中移除。使用 pygame.Rect.colliderect or pygame.Rect.contains to test whether a dot object is in the safe zone. Remove the dots form the list alldots that are not in the safe zone (see How to remove items from a list while iterating?):

def population(dots):

    safe_zone_rect = pygame.Rect(0, 0, 800, 100)
    
    for dot in dots:
        dot.spawnX += random.choice(dot.vel)
        dot.spawnY += random.choice(dot.vel)
        if dot.spawnX >= 800:
            dot.spawnX -= 5
        if dot.spawnY >= 600:
            dot.spawnY -= 5
        if dot.spawnX <= 0:
            dot.spawnX += 5
        if dot.spawnY <= 0:
            dot.spawnY += 5
        if dot.spawnX >= 0 and dot.spawnY >= 100:
            pass  #Here I want to delete the objects outside of this region

        dot_rect = pygame.Rect(dot.spawnX, dot.spawnY, 10, 10)
        # if not safe_zone_rect.colliderect(dot_rect):
        if not safe_zone_rect.contains(dot_rect):
            dots.remove(dot)

        drawdot(dot)

pygame.Rect.colliderect tests whether 2 rectangles intersect. pygame.Rect.contains 测试一个矩形是否完全位于另一个矩形内。