运行系统:macOS Sonoma 14.6.1
Python编译器:PyCharm 2024.1.4 (Community Edition)
Python版本:3.12
往期链接:
P146–Boid模型用于模拟鸟群行为
技术栈:pygame(版本2.6.0)+Boid模型
import pygame
import random
WIDTH, HEIGHT = 800, 600
BACKGROUND_COLOR = (255, 192, 203)
class Rectangle:
def __init__(self, x, y, w, h):
self.x = x
self.y = y
self.w = w
self.h = h
def contains(self, position):
return (self.x <= position.x < self.x + self.w and
self.y <= position.y < self.y + self.h)
def intersects(self, other):
return not (other.x + other.w < self.x or
other.x > self.x + self.w or
other.y + other.h < self.y or
other.y > self.y + self.h)
class Boid:
def __init__(self, x, y):
self.position = pygame.Vector2(x, y)
self.velocity = pygame.Vector2(random.uniform(-1, 1), random.uniform(-1, 1))
self.velocity.scale_to_length(random.uniform(2, 4))
def update(self, boids):
alignment = self.align(boids)
cohesion = self.cohere(boids)
separation = self.separate(boids)
self.velocity += alignment + cohesion + separation
self.velocity = self.velocity.normalize() * 4
self.position += self.velocity
self.wrap_around()
def align(self, boids):
perception_radius = 50
steering = pygame.Vector2(0, 0)
total = 0
for other in boids:
if other != self and self.position.distance_to(other.position) < perception_radius:
steering += other.velocity
total += 1
if total > 0:
steering /= total
steering = steering.normalize() * 4
steering -= self.velocity
return steering
return pygame.Vector2(0, 0)
def cohere(self, boids):
perception_radius = 100
steering = pygame.Vector2(0, 0)
total = 0
for other in boids:
if other != self and self.position.distance_to(other.position) < perception_radius:
steering += other.position
total += 1
if total > 0:
steering /= total
steering -= self.position
steering = steering.normalize() * 4
steering -= self.velocity
return steering
return pygame.Vector2(0, 0)
def separate(self, boids):
perception_radius =