-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfirefly_algorithm.py
68 lines (54 loc) · 2.12 KB
/
firefly_algorithm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# Explanation:
# 1. Fireflies: Each firefly has a light intensity and moves randomly across the screen.
# 2. Attraction: Fireflies with higher light intensity attract those with lower intensity, simulating natural behavior where fireflies follow light signals.
# 3. Movement: The movement is chaotic at first, but over time the fireflies tend to cluster around the brightest ones.
import pygame
import random
import math
# Configurações iniciais
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
NUM_FIREFLIES = 30
# Classe para vagalume
class Firefly:
def __init__(self):
self.x = random.randint(0, SCREEN_WIDTH)
self.y = random.randint(0, SCREEN_HEIGHT)
self.intensity = random.uniform(0.5, 1.0)
self.speed = 2
def move(self):
self.x += random.uniform(-1, 1) * self.speed
self.y += random.uniform(-1, 1) * self.speed
# Mantém o vagalume dentro da tela
if self.x < 0: self.x = 0
if self.x > SCREEN_WIDTH: self.x = SCREEN_WIDTH
if self.y < 0: self.y = 0
if self.y > SCREEN_HEIGHT: self.y = SCREEN_HEIGHT
def attract(self, other):
if self.intensity > other.intensity:
angle = math.atan2(self.y - other.y, self.x - other.x)
other.x += self.speed * math.cos(angle)
other.y += self.speed * math.sin(angle)
# Inicializa pygame
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Firefly Algorithm Simulation')
# Criação de vagalumes
fireflies = [Firefly() for _ in range(NUM_FIREFLIES)]
# Loop principal
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill(WHITE)
# Movimenta vagalumes e simula atração
for i, firefly in enumerate(fireflies):
firefly.move()
for j, other in enumerate(fireflies):
if i != j:
firefly.attract(other)
pygame.draw.circle(screen, (int(255 * firefly.intensity), 255, 0), (int(firefly.x), int(firefly.y)), 5)
pygame.display.flip()
pygame.time.delay(50)
pygame.quit()