Регистрация | Вход
import pygameimport randomWIDTH = 800HEIGHT = 600N = 50class Boid: def __init__(self): self.pos = pygame.math.Vector2(random.randint(0, WIDTH), random.randint(0, HEIGHT)) self.vel = pygame.math.Vector2(random.uniform(-1, 1), random.uniform(-1, 1)) self.acc = pygame.math.Vector2(0, 0) self.max_speed = 3 self.max_force = 0.1 self.radius = 5 def align(self, boids): steering = pygame.math.Vector2(0, 0) count = 0 for boid in boids: if boid != self and self.pos.distance_to(boid.pos) < 50: steering += boid.vel count += 1 if count > 0: steering /= count steering.scale_to_length(self.max_speed) steering -= self.vel steering.limit(self.max_force) return steering def cohesion(self, boids): steering = pygame.math.Vector2(0, 0) count = 0 for boid in boids: if boid != self and self.pos.distance_to(boid.pos) < 50: steering += boid.pos count += 1 if count > 0: steering /= count steering -= self.pos steering.scale_to_length(self.max_speed) steering -= self.vel steering.limit(self.max_force) return steering def separation(self, boids): steering = pygame.math.Vector2(0, 0) count = 0 for boid in boids: if boid != self and self.pos.distance_to(boid.pos) < 25: diff = self.pos - boid.pos diff /= self.pos.distance_to(boid.pos) steering += diff count += 1 if count > 0: steering /= count steering.scale_to_length(self.max_speed) steering -= self.vel steering.limit(self.max_force) return steering def update(self, boids): alignment = self.align(boids) cohesion = self.cohesion(boids) separation = self.separation(boids) self.acc = alignment + cohesion + separation self.vel += self.acc self.vel.limit(self.max_speed) self.pos += self.vel def draw(self, screen): pygame.draw.circle(screen, (255, 255, 255), (int(self.pos.x), int(self.pos.y)), self.radius)pygame.init()screen = pygame.display.set_mode((WIDTH, HEIGHT))pygame.display.set_caption("Boids")boids = [Boid() for _ in range(N)]running = Truewhile running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False screen.fill((0, 0, 0)) for boid in boids: boid.update(boids) boid.draw(screen) pygame.display.flip()pygame.quit()