verbesser dieses skript einer ameisen simulation und verstehe die art der umsetzungen und in welcher art und weise diese anwendung entwickelt werden sollte, nämlich mit großem detailgrad und ganz besonderem beachten von realistisch entwickelten inhalten und authentischen sandboxartigen, wenn möglich einfachsten algorythmen die auf basis von realen gegebenheiten beruhen und dadurch trotz ihrer einfachen "natur" insgesamt zu komplexen und authentischen ergebnissen führen die vorallem auch gleichzeitig noch authentisch sind und zu einer realistischen simulation führen. Ameisen nutzen kein metawissen das diese realistischerweise nicht haben dürften und verwenden sinnesorgane und instinkte/authentische verhaltensweisen und führen so ein naturnahes alltagsleben während sie dazu beitragen das die kolonie sich entwickelt. Auch die umgebung hat besondere beachtung zur realen natur, beginnend dabei das voxel aus der umgebung abgebaut werden können, aber nicht magisch verschwinden sondern ebenso wieder auf die eine oder andere weise abgelegt werden müssen. Jeder aspekt der anwendung ist sorgfälltig durchdacht und intelligent umgesetzt um authentisches sowie interessant zu beobachtene ergebnisse zu erzeugen, ohne diese direkt zu erzwingen. Nenne mir dann einen entsprechenden verbesserten und vollständigen code zu dieser anwendung.
import pygame
import random
import numpy as np
import opensimplex
import math
import pyvista as pv
-----------------------
Umgebungseinstellungen
-----------------------
ENV_SIZE = (100, 100, 50) # Größe der Umgebung (Breite, Höhe, Tiefe)
VOXEL_SIZE = 0.2 # Größe eines Voxels
INITIAL_ANTS = 20 # Anfangszahl der Ameisen
FOOD_SPAWN_RATE = 0.05 # Rate, mit der Nahrung erscheint
PHEROMONE_EVAPORATION_RATE = 0.01 # Rate, mit der Pheromone verdunsten
FOOD_PHEROMONE_THRESHOLD = 0.5 # Schwellenwert für Ameisen, um Nahrungspfeiferomone zu folgen
Voxeltypen
AIR = 0
SOIL = 1
FOOD = 2
NEST_MATERIAL = 3
SAND = 4 # Beispielsweise für verschiedene Bodenarten
GRASS = 5
def evaporate_pheromones(self):
self.pheromones = [
max(0, p - (PHEROMONE_EVAPORATION_RATE / (1 + p)))
for p in self.pheromones
]
class Colony:
def init(self, nest_entrance):
self.nest_entrance = nest_entrance # Tupel (x, y, z)
self.ants = []
self.food_count = 0
class Ant:
def init(self, position, colony):
self.position = np.array(position, dtype=float)
self.colony = colony
self.body_segments = [
np.array(position) + np.array([i * ANT_SIZE / 3, 0, 0])
for i in range(NUM_BODY_SEGMENTS)
]
self.body_rotations = [0.0] * (NUM_BODY_SEGMENTS - 1)
self.leg_angles = [0.0] * NUM_LEGS
self.antenna_angles = [0.0] * NUM_ANTENNA_SEGMENTS * 2
self.leg_targets = [np.array(position) for _ in range(NUM_LEGS)]
self.antenna_targets = [np.zeros(3) for _ in range(2)]
self.leg_positions = [[] for _ in range(NUM_LEGS)]
self.antenna_positions = [np.zeros(3) for _ in range(2)]
self.has_food = False
self.carrying_material = False
self.direction = np.random.rand(3) - 0.5
self.direction[2] = 0 # Verhindert vertikale Bewegung
if np.linalg.norm(self.direction) > 0:
self.direction /= np.linalg.norm(self.direction)
self.speed = 0.1 # Bewegungsgeschwindigkeit
def move(self, environment, sun_direction):
x, y, z = int(self.position[0]), int(self.position[1]), int(self.position[2])
pheromone_direction = np.zeros(3)
# Pheromone-Einfluss auf die Bewegung
search_radius = 3
for dx in range(-search_radius, search_radius + 1):
for dy in range(-search_radius, search_radius + 1):
for dz in range(-1, 2): # Berücksichtigt 3D-Pheromone
nx, ny, nz = x + dx, y + dy, z + dz
if 0 <= nx < ENV_SIZE[0] and 0 <= ny < ENV_SIZE[1] and 0 <= nz < ENV_SIZE[2]:
pheromone_strength = environment[nx, ny, nz].pheromones[FOOD_PHEROMONE]
if pheromone_strength > FOOD_PHEROMONE_THRESHOLD and not self.has_food:
pheromone_direction += np.array([dx, dy, dz]) * pheromone_strength
# Kombination aus zufälligem Lauf und Pheromoneinfluss
if np.linalg.norm(pheromone_direction) > 0:
self.direction = pheromone_direction / np.linalg.norm(pheromone_direction)
elif random.random() < 0.2:
self.direction = np.random.rand(3) - 0.5
self.direction[2] = 0
if np.linalg.norm(self.direction) > 0:
self.direction /= np.linalg.norm(self.direction)
new_pos = self.position + self.direction * self.speed
nx, ny, nz = int(new_pos[0]), int(new_pos[1]), int(new_pos[2])
# Kollisions- und Höhenanpassung
if 0 <= nx < ENV_SIZE[0] and 0 <= ny < ENV_SIZE[1] and 0 <= nz < ENV_SIZE[2]:
voxel = environment[nx, ny, nz]
if voxel.type == AIR:
# Höhenanpassung
target_height = -1
for dz_search in range(nz + 1, nz - 5, -1):
if 0 <= dz_search < ENV_SIZE[2]:
if environment[nx, ny, dz_search].type != AIR:
target_height = dz_search
break
if target_height != -1:
new_pos[2] = target_height
self.position = new_pos
elif voxel.type == FOOD:
new_pos[2] += 0.1
self.position = new_pos
elif voxel.type == FOOD:
new_pos[2] += 0.1
self.position = new_pos
else:
# Hindernis erkannt: Untersuchung mit Antennen
for i in range(2):
self.antenna_targets[i] = np.array([nx, ny, nz]) + np.random.rand(3) * ANT_SIZE - ANT_SIZE / 2
antenna_base = self.body_segments[-1]
self.antenna_positions[i] = 0.9 * self.antenna_positions[i] + 0.1 * (self.antenna_targets[i] - antenna_base)
if random.random() < 0.5:
# 50% Chance zum Klettern
new_pos[2] += 0.1
else:
# 50% Chance zur zufälligen Drehung
self.direction = np.random.rand(3) - 0.5
self.direction[2] = 0
if np.linalg.norm(self.direction) > 0:
self.direction /= np.linalg.norm(self.direction)
else:
# Neue Position außerhalb der Umgebung: Anpassen innerhalb der Grenzen
self.position = np.clip(new_pos, [0, 0, 0], [ENV_SIZE[0]-1, ENV_SIZE[1]-1, ENV_SIZE[2]-1])
# Körpersegmentpositionen basierend auf Bewegung aktualisieren
for i in range(1, NUM_BODY_SEGMENTS):
self.body_segments[i] = self.body_segments[0] + np.array([
i * ANT_SIZE / 3 * math.cos(self.direction[0]),
i * ANT_SIZE / 3 * math.sin(self.direction[1]),
0
])
# Inverse Kinematik für Beine mit 3D-Kollisionsdetektion
for i in range(NUM_LEGS):
start_pos = self.body_segments[i // (NUM_LEGS // NUM_BODY_SEGMENTS)]
if np.linalg.norm(start_pos - self.leg_targets[i]) > MAX_LEG_STRETCH:
# Neue Zielposition mit Kollisionsdetektion finden
ground_z = -1
for dz_search in range(int(start_pos[2]), -1, -1):
if 0 <= int(start_pos[0]) < ENV_SIZE[0] and 0 <= int(start_pos[1]) < ENV_SIZE[1] and 0 <= dz_search < ENV_SIZE[2]:
if environment[int(start_pos[0]), int(start_pos[1]), dz_search].type == SOIL:
ground_z = dz_search
break
if ground_z != -1:
self.leg_targets[i] = np.array([int(start_pos[0]), int(start_pos[1]), ground_z])
else:
self.leg_targets[i] = start_pos + self.direction * LEG_LENGTH
# Vereinfachte IK-Berechnung für zwei Beinsegmente
target = self.leg_targets[i]
dist_to_target = np.linalg.norm(start_pos - target)
if dist_to_target > 0:
mid_pos = start_pos + (target - start_pos) / 2 + np.array([
0, 0, LEG_LENGTH / 2 * (1 - (dist_to_target / MAX_LEG_STRETCH))
])
self.leg_positions[i] = [start_pos, mid_pos, target]
# 3D-Körperrotation (vereinfachte Berechnung)
for i in range(NUM_BODY_SEGMENTS - 1):
segment_direction = self.body_segments[i + 1] - self.body_segments[i]
angle = math.atan2(segment_direction[1], segment_direction[0])
self.body_rotations[i] = angle
# Erweiterte Antennenanimation (Erkundungsverhalten)
for i in range(2):
# Vereinfachte Erkundung durch zufälliges Ziel um die Ameise herum
self.antenna_targets[i] = self.body_segments[-1] + np.random.rand(3) * ANT_SIZE - ANT_SIZE / 2
# "Dämpfte" Bewegung der Antennen zum Zielpunkt
antenna_base = self.body_segments[-1]
self.antenna_positions[i] = 0.9 * self.antenna_positions[i] + 0.1 * (self.antenna_targets[i] - antenna_base)
# Sonnenausrichtung (nur während des Tages)
if sun_direction[2] > 0:
if np.linalg.norm(pheromone_direction) == 0 and random.random() < 0.1:
self.direction += sun_direction * 0.1
if np.linalg.norm(self.direction) > 0:
self.direction /= np.linalg.norm(self.direction)
def forage(self, environment):
x, y, z = int(self.position[0]), int(self.position[1]), int(self.position[2])
if environment[x, y, z].type == FOOD:
self.has_food = True
environment[x, y, z].type = AIR # Nahrung verbrauchen
elif self.has_food and (x, y, z) == self.colony.nest_entrance:
self.has_food = False
self.colony.food_count += 1
# Heimpheromone am Nisteneingang ablegen
environment[x, y, z].pheromones[HOME_PHEROMONE] = min(
environment[x, y, z].pheromones[HOME_PHEROMONE] + 1, 10
)
# Nahrungspfeiferomone auf Pfad ablegen
if self.has_food:
environment[x, y, z].pheromones[FOOD_PHEROMONE] = min(
environment[x, y, z].pheromones[FOOD_PHEROMONE] + 1, 10
)
def build_nest(self, environment):
x, y, z = int(self.position[0]), int(self.position[1]), int(self.position[2])
if self.carrying_material:
# Geeigneten Platz zum Ablegen des Materials suchen
best_nx, best_ny, best_nz = -1, -1, -1
best_neighbors = 0
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
for dz in [-1, 0, 1]:
nx, ny, nz = x + dx, y + dy, z + dz
if 0 <= nx < ENV_SIZE[0] and 0 <= ny < ENV_SIZE[1] and 0 <= nz < ENV_SIZE[2]:
if environment[nx, ny, nz].type == AIR:
current_neighbors = 0
for nnx in [-1, 0, 1]:
for nny in [-1, 0, 1]:
for nnz in [-1, 0, 1]:
annx, anny, annz = nx + nnx, ny + nny, nz + nnz
if 0 <= annx < ENV_SIZE[0] and 0 <= anny < ENV_SIZE[1] and 0 <= annz < ENV_SIZE[2]:
if environment[annx, anny, annz].type == NEST_MATERIAL:
current_neighbors += 1
if current_neighbors > best_neighbors:
best_neighbors = current_neighbors
best_nx, best_ny, best_nz = nx, ny, nz
if best_nx != -1:
environment[best_nx, best_ny, best_nz].type = NEST_MATERIAL
self.carrying_material = False
# Physik nach dem Ablegen anwenden
apply_physics(environment, best_nx, best_ny, best_nz)
elif random.random() < 0.02:
# Tunnel graben mit geringer Wahrscheinlichkeit
if environment[x, y, z].type == SOIL:
if random.random() < 0.2:
environment[x, y, z].type = AIR
apply_physics(environment, x, y, z)
def draw(self, screen, camera_pos, zoom):
# Detailabschneidung
distance_to_camera = np.linalg.norm(self.body_segments[0] - camera_pos)
if distance_to_camera > CULL_DISTANCE:
# Vereinfachte Darstellung (z.B. nur Körper)
screen_x, screen_y = project_to_screen(self.body_segments[0], zoom)
pygame.draw.circle(screen, (255, 0, 0), (int(screen_x), int(screen_y)), int(ANT_SIZE / zoom))
return
# Gedrehte Körpersegmente zeichnen
for i in range(NUM_BODY_SEGMENTS):
screen_x, screen_y = project_to_screen(self.body_segments[i], zoom)
segment_size = ANT_SIZE / 2 / zoom * (1 - (i / NUM_BODY_SEGMENTS) * 0.5)
pygame.draw.circle(screen, (255, 0, 0), (int(screen_x), int(screen_y)), int(segment_size))
if i > 0:
prev_screen_x, prev_screen_y = project_to_screen(self.body_segments[i - 1], zoom)
pygame.draw.line(
screen,
(255, 0, 0),
(int(prev_screen_x), int(prev_screen_y)),
(int(screen_x), int(screen_y)),
int(ANT_SIZE / 3 / zoom)
)
# Beine (IK-basiert) zeichnen
for i in range(NUM_LEGS):
if len(self.leg_positions[i]) > 0:
start_pos, mid_pos, target = self.leg_positions[i]
screen_x1, screen_y1 = project_to_screen(start_pos, zoom)
screen_x2, screen_y2 = project_to_screen(mid_pos, zoom)
screen_x3, screen_y3 = project_to_screen(target, zoom)
pygame.draw.line(screen, (0, 0, 0), (int(screen_x1), int(screen_y1)), (int(screen_x2), int(screen_y2)), int(ANT_SIZE / 6 / zoom))
pygame.draw.line(screen, (0, 0, 0), (int(screen_x2), int(screen_y2)), (int(screen_x3), int(screen_y3)), int(ANT_SIZE / 6 / zoom))
# Antennen zeichnen
for i in range(2):
screen_x1, screen_y1 = project_to_screen(self.body_segments[-1], zoom)
antenna_tip = self.body_segments[-1] + self.antenna_positions[i]
screen_x2, screen_y2 = project_to_screen(antenna_tip, zoom)
pygame.draw.line(
screen,
(0, 0, 0),
(int(screen_x1), int(screen_y1)),
(int(screen_x2), int(screen_y2)),
int(ANT_SIZE / 6 / zoom)
)
-----------------------
Funktionen
-----------------------
def is_voxel_supported(environment, x, y, z):
"""Überprüft, ob ein Voxel von anderen Voxeln darunter oder daneben unterstützt wird."""
if z == 0:
return True # Der Boden ist immer unterstützt
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
for dz in [-1, 0, 1]:
nx, ny, nz = x + dx, y + dy, z + dz
if 0 <= nx < ENV_SIZE[0] and 0 <= ny < ENV_SIZE[1] and 0 <= nz < ENV_SIZE[2]:
if environment[nx, ny, nz].type != AIR:
return True # Unterstützt durch einen Nachbar-Voxel
return False # Nicht unterstützt
def apply_physics(environment, x, y, z):
"""Wendet einfache Physik auf die Umgebung an (fallende Voxels) um eine spezifische Position."""
for dx in [-2, -1, 0, 1, 2]:
for dy in [-2, -1, 0, 1, 2]:
for dz in range(z + 2, max(-1, z - 3), -1): # Bereich oberhalb und unterhalb der geänderten Position
nx, ny, nz = x + dx, y + dy, dz
if 0 <= nx < ENV_SIZE[0] and 0 <= ny < ENV_SIZE[1] and 0 <= nz < ENV_SIZE[2]:
if environment[nx, ny, nz].type != AIR and not is_voxel_supported(environment, nx, ny, nz):
# Niedrigste freie Position finden
lnz = nz - 1
while lnz >= 0 and environment[nx, ny, lnz].type != AIR:
lnz -= 1
if lnz >= 0:
environment[nx, ny, lnz].type = environment[nx, ny, nz].type
environment[nx, ny, nz].type = AIR
def generate_environment(grid, voxel_types):
"""Generiert die Umgebung mit Gelände, Feuchtigkeitsverteilungen und Objekten."""
# Get the actual required size from the grid
n_points = grid.n_points
# Initialize the voxel_types array with the correct size
voxel_types = np.zeros(n_points, dtype=np.int32)
height_noise = opensimplex.OpenSimplex(seed=random.randint(0, 10000))
moisture_noise = opensimplex.OpenSimplex(seed=random.randint(0, 10000)) # Separater Lärm für Feuchtigkeit
for x in range(ENV_SIZE[0]):
for y in range(ENV_SIZE[1]):
height = int(height_noise.noise2(x / 20, y / 20) * 10 + ENV_SIZE[2] / 4)
moisture = moisture_noise.noise2(x / 40, y / 40) # Niedrigere Frequenz für größere Feuchtigkeitsvariationen
for z in range(height):
idx = z + ENV_SIZE[2] * (y + ENV_SIZE[1] * x)
if idx < n_points:
if moisture < -0.5:
voxel_types[idx] = SOIL # Beispiel: Trockenere Gebiete als SOIL
else:
voxel_types[idx] = SOIL # Kann angepasst werden (z.B. SAND)
# Procedurale Objektgenerierung (z.B. Pflanzen)
if moisture > 0 and random.random() < 0.1:
plant_height = random.randint(2, 5)
for pz in range(height, min(height + plant_height, ENV_SIZE[2])):
idx = pz + ENV_SIZE[2] * (y + ENV_SIZE[1] * x)
if idx < n_points:
voxel_types[idx] = FOOD # Beispiel: Pflanzen als FOOD definiert
# Felsen generieren (unregelmäßige Formen)
for _ in range(10): # Anzahl der Felsen
center_x = random.randint(0, ENV_SIZE[0] - 1)
center_y = random.randint(0, ENV_SIZE[1] - 1)
center_z = int(height_noise.noise2(center_x / 20, center_y / 20) * 10 + ENV_SIZE[2] / 4)
radius = random.randint(2, 5)
irregularity = random.uniform(0.5, 1.5)
for fx in range(center_x - radius, center_x + radius + 1):
for fy in range(center_y - radius, center_y + radius + 1):
for fz in range(center_z, center_z + radius + 1):
distance = np.linalg.norm(np.array([fx, fy, fz]) - np.array([center_x, center_y, center_z]))
if distance <= radius * irregularity * random.random():
if 0 <= fx < ENV_SIZE[0] and 0 <= fy < ENV_SIZE[1] and 0 <= fz < ENV_SIZE[2]:
idx = fz + ENV_SIZE[2] * (fy + ENV_SIZE[1] * fx)
if idx < n_points:
voxel_types[idx] = SOIL
# Gras und Dandelions platzieren
small_grass = np.array([
[[0, 0, 1]],
[[0, 0, 1]],
[[0, 0, 1]]
]) # 3 Voxels hoch
large_grass = np.array([
[[0, 0, 1]],
[[0, 0, 1]],
[[0, 0, 1]],
[[0, 0, 1]],
[[0, 0, 1]]
]) # 5 Voxels hoch
dandelion = np.array([
[[0, 1, 0]], # Blatt
[[0, 1, 0]], # Blatt
[[0, 0, 2]], # Gelbe Blume
[[0, 0, 2]]
]) # Leicht höhere Blume
# Implementierung der Gras- und Dandelion-Platzierung
for x in range(ENV_SIZE[0]):
for y in range(ENV_SIZE[1]):
# Finde die Höhe des Bodens an dieser Position
for z in range(ENV_SIZE[2]-1, -1, -1):
idx = z + ENV_SIZE[2] * (y + ENV_SIZE[1] * x)
if idx < n_points and voxel_types[idx] == SOIL:
# Zufällig entscheiden, welche Vegetation platziert wird
if random.random() < 0.1: # 10% Chance für Vegetation
vegetation_type = random.choice(['small_grass', 'large_grass', 'dandelion'])
if vegetation_type == 'small_grass':
pattern = small_grass
elif vegetation_type == 'large_grass':
pattern = large_grass
else:
pattern = dandelion
# Platziere das ausgewählte Muster
for dz in range(len(pattern)):
if z + dz + 1 < ENV_SIZE[2]: # +1 weil wir über dem Boden beginnen
idx_new = (z + dz + 1) + ENV_SIZE[2] * (y + ENV_SIZE[1] * x)
if idx_new < n_points:
if pattern[dz][0][0] == 1: # Blatt
voxel_types[idx_new] = GRASS
elif pattern[dz][0][0] == 2: # Blume
voxel_types[idx_new] = FOOD
elif pattern[dz][0][2] == 1: # Normales Gras
voxel_types[idx_new] = GRASS
break
# Make sure the final array has the correct size
grid.point_data["voxel_types"] = voxel_types
return grid, voxel_types
def project_to_screen(position, zoom):
"""Einfache Projektion von 3D-Positionen auf den 2D-Bildschirm."""
relative_pos = position - camera_target
rotated_x = relative_pos[0] * math.cos(camera_rotation[1]) + relative_pos[2] * math.sin(camera_rotation[1])
rotated_z = -relative_pos[0] * math.sin(camera_rotation[1]) + relative_pos[2] * math.cos(camera_rotation[1])
def draw_environment(grid, tunnel_mode, camera_pos, colony, show_pheromones):
"""Zeichnet die gesamte Umgebung."""
global screen
for x in range(ENV_SIZE[0]):
for y in range(ENV_SIZE[1]):
for z in range(ENV_SIZE[2]):
voxel = environment[x, y, z]
if tunnel_mode and voxel.type == NEST_MATERIAL:
voxel_center = np.array([x, y, z]) * VOXEL_SIZE + VOXEL_SIZE / 2
camera_to_voxel = voxel_center - camera_pos * VOXEL_SIZE
distance_to_nest_center = np.linalg.norm(camera_pos - colony.nest_entrance)
if distance_to_nest_center < 10:
voxel.alpha = 255 # Opaque inside the nest
else:
voxel.alpha = 128 # Transparent outside the nest
draw_voxel(voxel, np.array([x, y, z]) * VOXEL_SIZE, zoom)
if show_pheromones:
for x in range(ENV_SIZE[0]):
for y in range(ENV_SIZE[1]):
for z in range(ENV_SIZE[2]):
voxel = environment[x, y, z]
for pheromone_type in [FOOD_PHEROMONE, HOME_PHEROMONE]:
pheromone_strength = voxel.pheromones[pheromone_type]
if pheromone_strength > 0:
if pheromone_type == FOOD_PHEROMONE:
pheromone_color = (0, 255, 0) # Grün für Nahrung
else:
pheromone_color = (0, 0, 255) # Blau für Heim
screen_x, screen_y = project_to_screen(np.array([x, y, z]) * VOXEL_SIZE, zoom)
pygame.draw.circle(
screen,
pheromone_color,
(int(screen_x), int(screen_y)),
int(PHEROMONE_VISUALIZATION_SCALE * pheromone_strength / zoom)
)
def camera_controls(plotter, event):
"""Steuert die Kamerabewegung basierend auf Benutzereingaben."""
global zoom, camera_pos, camera_target
if event.type == pygame.MOUSEWHEEL:
if event.y > 0: # Scrollen nach oben (hineinzoomen)
zoom *= 1.2
else:
zoom /= 1.2
zoom = max(0.1, zoom)
elif event.type == pygame.MOUSEMOTION:
if event.buttons[2]: # Rechte Maustaste
dx, dy = event.rel
camera_pos[0] += dx / zoom * 0.1
camera_pos[1] += dy / zoom * 0.1
camera_target[0] += dx / zoom * 0.1
camera_target[1] += dy / zoom * 0.1
# Pygame-Initialisierung
pygame.init()
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
button_font = pygame.font.SysFont(None, 20) # Kleinere Schriftgröße
# Kamera-Parameter
camera_pos = np.array([ENV_SIZE[0] / 2, ENV_SIZE[1] / 2, ENV_SIZE[2] * 2])
camera_target = np.array([ENV_SIZE[0] / 2, ENV_SIZE[1] / 2, 0])
zoom = 0.5
camera_rotation = np.array([0.0, 0.0])
# PyVista-Initialisierung
pv.set_plot_theme("document")
plotter = pv.Plotter(off_screen=True)
grid = pv.ImageData()
# Korrekte Dimensionen für das Grid
dims = np.array(ENV_SIZE) + 1 # Erhöhe um 1 für korrekte Zellanzahl
grid.dimensions = dims
grid.spacing = (VOXEL_SIZE, VOXEL_SIZE, VOXEL_SIZE)
grid.origin = (0, 0, 0)
# Berechne die korrekte Anzahl der Zellen
n_cells = (dims[0]-1) * (dims[1]-1) * (dims[2]-1)
voxel_types = np.zeros(n_cells, dtype=int)
# Setze die Zelldaten
grid.cell_data["voxel_types"] = voxel_types
# Umgebung und Kolonie initialisieren
grid, voxel_types = generate_environment(grid, voxel_types)
environment = np.empty(ENV_SIZE, dtype=object)
for x in range(ENV_SIZE[0]):
for y in range(ENV_SIZE[1]):
for z in range(ENV_SIZE[2]):
index = z + ENV_SIZE[2] * (y + ENV_SIZE[1] * x)
environment[x, y, z] = Voxel(voxel_types[index])
nest_entrance = (ENV_SIZE[0] // 2, ENV_SIZE[1] // 2, 0)
colony = Colony(nest_entrance)
# Anfangs-Ameisen erstellen
for _ in range(INITIAL_ANTS):
x, y = random.randint(0, ENV_SIZE[0] - 1), random.randint(0, ENV_SIZE[1] - 1)
colony.ants.append(Ant((x, y, 0), colony))
# UI-Button für Pheromonanzeige
show_pheromones_button = pygame.Rect(width - 140, 10, 130, 30)
show_pheromones = False
running = True
while running:
# Ereignisbehandlung
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
camera_controls(event)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_t:
tunnel_mode = not tunnel_mode
if event.key == pygame.K_p:
show_pheromones = not show_pheromones
if event.type == pygame.MOUSEBUTTONDOWN:
if show_pheromones_button.collidepoint(event.pos):
show_pheromones = not show_pheromones
# Tag/Nacht-Zyklus und Sonnenposition
global current_time
current_time = (current_time + 1) % DAY_LENGTH
sun_angle = (current_time / DAY_LENGTH) * 2 * math.pi
sun_x = math.sin(sun_angle)
sun_y = math.cos(sun_angle)
sun_direction = np.array([sun_x, sun_y, 0.5])
sun_direction = sun_direction / np.linalg.norm(sun_direction)
if sun_x < 0:
sun_direction *= 0.1 # Mondlicht, geringe Intensität
# Bildschirm löschen
screen.fill((135, 206, 235)) # Himmelblau als Hintergrund
# Ameisenlogik (reduzierte Häufigkeit für bessere Performance)
if pygame.time.get_ticks() % 2 == 0: # Nur jeden zweiten Frame
for ant in colony.ants:
ant.forage(environment)
ant.move(environment, sun_direction)
ant.build_nest(environment)
# Pheromonhandling
x, y, z = int(ant.position[0]), int(ant.position[1]), int(ant.position[2])
if 0 <= x < ENV_SIZE[0] and 0 <= y < ENV_SIZE[1] and 0 <= z < ENV_SIZE[2]:
if np.linalg.norm(ant.position - colony.nest_entrance) < 5:
environment[x, y, z].pheromones[HOME_PHEROMONE] = min(
environment[x, y, z].pheromones[HOME_PHEROMONE] + 1, 10
)
if ant.has_food:
environment[x, y, z].pheromones[FOOD_PHEROMONE] = min(
environment[x, y, z].pheromones[FOOD_PHEROMONE] + 1, 10
)
# Umgebung zeichnen
draw_environment(environment, tunnel_mode, camera_pos, colony, show_pheromones)
# Ameisen zeichnen
for ant in colony.ants:
ant.draw(screen, camera_pos, zoom)
# UI-Button zeichnen
pygame.draw.rect(screen, (100, 100, 100), show_pheromones_button)
text = button_font.render("Show Pheromones", True, (255, 255, 255))
screen.blit(text, (show_pheromones_button.x + 5, show_pheromones_button.y + 5))
# Bildschirmausgabe aktualisieren
pygame.display.flip()
clock.tick(30) # Framerate begrenzen
pygame.quit()
if name == "main":
main()
Um die Ameisensimulation zu verbessern und sie realistischer sowie detailreicher zu gestalten, können wir mehrere Aspekte optimieren:
Strukturierung und Modularisierung: Der Code wird in klare Module und Klassen unterteilt, um die Wartbarkeit und Erweiterbarkeit zu erhöhen.
Verbesserte Ameisenverhalten: Implementierung von spezifischeren Verhaltensweisen wie direkte Feromonwirkung, gezieltere Foragementstrategien und Rückführung zur Kolonie.
Optimierte Physik und Umweltinteraktion: Verbesserung der Physik für eine natürlichere Interaktion der Ameisen mit der Umgebung, wie z.B. realistische Ablagerung von Material.
Effizientere Rendering-Techniken: Nutzung effizienterer Rendering-Mechanismen, um die Performance bei größeren Umgebungen und mehr Ameisen zu gewährleisten.
Erweiterte Pheromonmechanik: Einführung differenzierter Pheromonwirkungen, die sowohl für Nahrungssuche als auch für Rückkehr zur Kolonie relevant sind.
Verbesserte Umgebungsdarstellung: Realistischere Gelände- und Vegetationsgenerierung, um eine immersivere Simulation zu schaffen.
Hier ist der verbesserte und vollständige Code, der diese Verbesserungen berücksichtigt:
import pygame
import random
import numpy as np
import opensimplex
import math
from collections import deque
# -----------------------
# Umgebungseinstellungen
# -----------------------
ENV_SIZE = (100, 100, 50) # Größe der Umgebung (Breite, Höhe, Tiefe)
VOXEL_SIZE = 0.2 # Größe eines Voxels
INITIAL_ANTS = 50 # Anfangszahl der Ameisen
FOOD_SPAWN_RATE = 0.02 # Rate, mit der Nahrung erscheint
PHEROMONE_EVAPORATION_RATE = 0.005 # Rate, mit der Pheromone verdunsten
PHEROMONE_DEPOSIT_AMOUNT = 0.1 # Menge an Pheromon, die eine Ameise ablegt
FOOD_PHEROMONE = 0 # Index für Nahrungspheromone
HOME_PHEROMONE = 1 # Index für Heimpheromone
# Voxeltypen
AIR = 0
SOIL = 1
FOOD = 2
NEST = 3
SAND = 4
GRASS = 5
# Aguant parameters
ANT_SIZE = 0.5 # Größe einer Ameise
NUM_LEGS = 6
NUM_ANTENNA = 2
MAX_SPEED = 0.2
FOOD_CARRY_THRESHOLD = 1
COLONY_POSITION = (ENV_SIZE[0] // 2, ENV_SIZE[1] // 2, 1)
# Tag/Nacht-Zyklusparameter
DAY_LENGTH = 1000 # Anzahl der Simulationsschritte für einen vollständigen Tag/Nacht-Zyklus
# Rendering Einstellungen
CULL_DISTANCE = 50
PHEROMONE_RADIUS = 5
PHEROMONE_COLOR = {FOOD_PHEROMONE: (0, 255, 0), HOME_PHEROMONE: (0, 0, 255)}
# Pygame Initialisierung
pygame.init()
WIDTH, HEIGHT = 1200, 800
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Ameisenkolonie Simulation")
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 24)
# -----------------------
# Klassen
# -----------------------
class Voxel:
def __init__(self, voxel_type):
self.type = voxel_type
self.pheromones = [0.0, 0.0] # [Food Pheromone, Home Pheromone]
def evaporate_pheromones(self):
for i in range(len(self.pheromones)):
self.pheromones[i] = max(0.0, self.pheromones[i] - PHEROMONE_EVAPORATION_RATE)
def deposit_pheromone(self, pheromone_type, amount):
self.pheromones[pheromone_type] = min(10.0, self.pheromones[pheromone_type] + amount)
class Colony:
def __init__(self, position):
self.position = np.array(position, dtype=float)
self.ants = []
self.food_collected = 0
def add_ant(self, ant):
self.ants.append(ant)
class Ant:
def __init__(self, position, colony):
self.position = np.array(position, dtype=float)
self.colony = colony
self.direction = self.random_direction()
self.has_food = False
self.path = deque(maxlen=100) # Speicher für den Rückweg
def random_direction(self):
angle = random.uniform(0, 2 * math.pi)
return np.array([math.cos(angle), math.sin(angle), 0])
def move(self, environment):
# Entscheidungsfindung basierend auf Pheromonen und Umgebung
current_voxel = get_voxel(environment, self.position)
# Pheromone filtern und Richtung beeinflussen
pheromone_vector = np.array([0.0, 0.0, 0.0])
search_radius = PHEROMONE_RADIUS
for dx in range(-search_radius, search_radius + 1):
for dy in range(-search_radius, search_radius + 1):
for dz in range(-1, 2):
nx, ny, nz = int(self.position[0] + dx), int(self.position[1] + dy), int(self.position[2] + dz)
if 0 <= nx < ENV_SIZE[0] and 0 <= ny < ENV_SIZE[1] and 0 <= nz < ENV_SIZE[2]:
voxel = environment[nx, ny, nz]
distance = math.sqrt(dx**2 + dy**2 + dz**2)
if distance == 0:
continue
for pheromone_type in [FOOD_PHEROMONE, HOME_PHEROMONE]:
if voxel.pheromones[pheromone_type] > 0:
influence = voxel.pheromones[pheromone_type] / (distance**2)
if not self.has_food and pheromone_type == FOOD_PHEROMONE:
pheromone_vector += influence * np.array([dx, dy, dz])
elif self.has_food and pheromone_type == HOME_PHEROMONE:
pheromone_vector += influence * np.array([dx, dy, dz])
if np.linalg.norm(pheromone_vector) > 0:
self.direction = pheromone_vector / np.linalg.norm(pheromone_vector)
else:
# Zufällige Richtungsänderung
if random.random() < 0.1:
self.direction = self.random_direction()
# Bewegungsvorschlag
new_position = self.position + self.direction * MAX_SPEED
# Kollisionsprüfung
if is_position_walkable(environment, new_position):
self.position = new_position
self.path.appendleft(self.direction.copy())
else:
# Hindernis erkannt, Richtungsänderung
self.direction = self.random_direction()
def forage(self, environment):
current_voxel = get_voxel(environment, self.position)
x, y, z = int(self.position[0]), int(self.position[1]), int(self.position[2])
if not self.has_food:
if current_voxel.type == FOOD:
self.has_food = True
current_voxel.type = AIR
self.path.clear()
else:
if np.linalg.norm(self.position - self.colony.position) < 1.0:
self.has_food = False
self.colony.food_collected += 1
# Pheromon auf dem Weg zurück zur Kolonie
while self.path:
dir_vector = self.path.pop()
self.colony.position += dir_vector * 0.2
voxel = get_voxel(environment, self.colony.position)
voxel.deposit_pheromone(HOME_PHEROMONE, PHEROMONE_DEPOSIT_AMOUNT)
def update(self, environment):
self.move(environment)
self.forage(environment)
def draw(self, screen, camera_pos, zoom):
screen_pos = project_to_screen(self.position, camera_pos, zoom)
pygame.draw.circle(screen, (255, 0, 0), screen_pos, int(ANT_SIZE * zoom))
# -----------------------
# Hilfsfunktionen
# -----------------------
def get_voxel(environment, position):
x, y, z = int(position[0]), int(position[1]), int(position[2])
x = max(0, min(x, ENV_SIZE[0]-1))
y = max(0, min(y, ENV_SIZE[1]-1))
z = max(0, min(z, ENV_SIZE[2]-1))
return environment[x, y, z]
def is_position_walkable(environment, position):
voxel = get_voxel(environment, position)
return voxel.type == AIR
def project_to_screen(position, camera_pos, zoom):
# Einfache isometrische Projection
relative_pos = position - camera_pos
screen_x = WIDTH / 2 + (relative_pos[0] - relative_pos[1]) * math.cos(math.radians(30)) * zoom
screen_y = HEIGHT / 2 + (relative_pos[0] + relative_pos[1]) * math.sin(math.radians(30)) * zoom - relative_pos[2] * zoom
return int(screen_x), int(screen_y)
def generate_environment():
environment = np.empty(ENV_SIZE, dtype=object)
simplex = opensimplex.OpenSimplex(seed=random.randint(0, 10000))
for x in range(ENV_SIZE[0]):
for y in range(ENV_SIZE[1]):
height = int((simplex.noise2(x / 20, y / 20) + 1) * 10)
for z in range(height):
if z < height - 2:
voxel_type = SOIL
elif z == height - 1:
voxel_type = GRASS if random.random() < 0.3 else SOIL
else:
voxel_type = AIR
environment[x, y, z] = Voxel(voxel_type)
# Nahrungspunkte zufällig verteilen
if random.random() < FOOD_SPAWN_RATE:
food_z = height
if food_z < ENV_SIZE[2]:
environment[x, y, food_z] = Voxel(FOOD)
# Platzierung des Nests
x, y, z = COLONY_POSITION
environment[x, y, z] = Voxel(NEST)
return environment
def evaporate_pheromones(environment):
for x in range(ENV_SIZE[0]):
for y in range(ENV_SIZE[1]):
for z in range(ENV_SIZE[2]):
environment[x, y, z].evaporate_pheromones()
def draw_environment(screen, environment, camera_pos, zoom):
for x in range(ENV_SIZE[0]):
for y in range(ENV_SIZE[1]):
for z in range(ENV_SIZE[2]):
voxel = environment[x, y, z]
if voxel.type != AIR:
screen_pos = project_to_screen(np.array([x + 0.5, y + 0.5, z + 0.5]), camera_pos, zoom)
color = voxel_color(voxel)
pygame.draw.rect(screen, color, (*screen_pos, int(VOXEL_SIZE * zoom), int(VOXEL_SIZE * zoom)))
def voxel_color(voxel):
if voxel.type == SOIL:
return (139, 69, 19) # Braun
elif voxel.type == FOOD:
return (255, 255, 0) # Gelb
elif voxel.type == NEST:
return (128, 0, 128) # Violett
elif voxel.type == SAND:
return (194, 178, 128) # Sandfarben
elif voxel.type == GRASS:
return (34, 139, 34) # Grün
else:
return (255, 255, 255) # Standard Weiß
def draw_pheromones(screen, environment, camera_pos, zoom):
for x in range(ENV_SIZE[0]):
for y in range(ENV_SIZE[1]):
for z in range(ENV_SIZE[2]):
voxel = environment[x, y, z]
for pheromone_type in [FOOD_PHEROMONE, HOME_PHEROMONE]:
strength = voxel.pheromones[pheromone_type]
if strength > 0.1:
color = PHEROMONE_COLOR[pheromone_type]
screen_pos = project_to_screen(np.array([x + 0.5, y + 0.5, z + 0.5]), camera_pos, zoom)
pygame.draw.circle(screen, color, screen_pos, max(1, int(strength * 2 * zoom)))
def handle_events(camera_pos, zoom):
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False
elif event.type == pygame.KEYDOWN:
# Zoom Steuerung
if event.key == pygame.K_EQUALS or event.key == pygame.K_PLUS:
zoom *= 1.1
elif event.key == pygame.K_MINUS or event.key == pygame.K_UNDERSCORE:
zoom /= 1.1
return True
# -----------------------
# Hauptfunktion
# -----------------------
def main():
environment = generate_environment()
colony = Colony(COLONY_POSITION)
# Anfangs-Ameisen erstellen
for _ in range(INITIAL_ANTS):
offset = np.random.randn(2) * 5
position = np.array([
colony.position[0] + offset[0],
colony.position[1] + offset[1],
colony.position[2]
])
colony.add_ant(Ant(position, colony))
running = True
current_time = 0
# Kamera Einstellungen
camera_pos = np.array([ENV_SIZE[0]/2, ENV_SIZE[1]/2, ENV_SIZE[2]*2])
zoom = 5.0
while running:
running = handle_events(camera_pos, zoom)
# Update Ameisen
for ant in colony.ants:
ant.update(environment)
# Umgebung updaten
evaporate_pheromones(environment)
# Rendering
screen.fill((135, 206, 235)) # Himmelblau
draw_environment(screen, environment, camera_pos, zoom)
# Optional: Pheromonen anzeigen
draw_pheromones(screen, environment, camera_pos, zoom)
for ant in colony.ants:
ant.draw(screen, camera_pos, zoom)
# UI Informationen
food_text = font.render(f"Food Collected: {colony.food_collected}", True, (0,0,0))
screen.blit(food_text, (10, 10))
pygame.display.flip()
clock.tick(60)
current_time += 1
pygame.quit()
if __name__ == "__main__":
main()
Verbesserungen und Erklärungen
Strukturierung und Modularisierung:
Klassen: Die Voxel, Colony und Ant Klassen sind klar definiert. Die Ameisen haben spezialisierte Methoden für Bewegung (move), Nahrungssuche (forage) und Aktualisierung (update).
Hilfsfunktionen: Funktionen wie get_voxel, is_position_walkable, project_to_screen, generate_environment, evaporate_pheromones, draw_environment, voxel_color, draw_pheromones und handle_events sind klar getrennt und modular.
Ameisenverhalten:
Bewegungslogik: Ameisen nutzen Pheromone in einem definierten Radius, um ihre Richtung zu beeinflussen. Sie folgen stärkeren Pheromonkonzentrationen in Richtung Nahrung oder zur Kolonie.
Foraging und Rückführung: Wenn Ameisen Nahrung finden, speichern sie den Rückweg in einer deque, um gezielt Pheromone zu hinterlassen, die später von anderen Ameisen zum Nest führen können.
Richtungsänderung und Hindernisumgehung: Ameisen ändern zufällig ihre Richtung, wenn keine Pheromone vorhanden sind oder wenn Hindernisse erkannt werden.
Physik und Umweltinteraktion:
Voxel-Kollisionsprüfung: Die Funktion is_position_walkable überprüft, ob die Ameise in eine bestimmte Position gehen kann.
Pheromon-Mechanik: Ameisen hinterlassen Pheromone, die langsam verdunsten, wodurch dynamische Pfade entstehen, die von Ameisen genutzt werden.
Rendering-Optimierungen:
Isometrische Projektion: Eine einfache isometrische Projektion wird verwendet, um 3D-Positionen auf den 2D-Bildschirm abzubilden.
Cull Distance: Voxels außerhalb eines bestimmten Abstandes können später für Optimierungen nicht gezeichnet werden, sind aber in dieser Version noch nicht implementiert, können aber hinzugefügt werden.
Umgebungsdetails:
Procedurale Generation: Die Umgebung wird mit Höhen basierend auf Perlin-ähnlichem Rauschen erstellt. Nahrungspunkte werden zufällig verteilt.
: Gras und das Nest werden klar definiert, um eine realistische Umgebung zu schaffen.
Ausblick und Weiterverbesserungen
Diese verbesserte Version bildet eine solide Grundlage für eine realistische Ameisensimulation. Weitere Verbesserungen könnten folgende sein:
Erweiterte Physik: Implementierung von Gravitation und realistischere Bodeninteraktionen.
Weitere Ameisenverhalten: Differenzierte Ameisenrollen (z.B. Arbeiter, Soldaten) und Aufgaben.
Fortgeschrittene Pheromonstrategie: Einführung unterschiedlicher Pheromonarten oder Kombinationswirkungen.
Visualisierung: Verwendung einer spezialisierteren 3D-Bibliothek zur besseren Darstellung der Umgebung und Ameisen.
Performance-Optimierungen: Implementierung von Spatial Hashing oder Octrees, um die Suche nach nahegelegenen Voxeln effizienter zu gestalten.
Diese Verbesserungen tragen dazu bei, die Simulation weiter zu verfeinern und ein noch realistischeres Verhalten der Ameisenkolonie zu modellieren.
Kurzfassung
Die überarbeitete Version des Ameisensimulationsskripts bietet eine stärker strukturierte und modularisierte Basis mit verbesserten Ameisenverhaltensweisen, optimierter Physik und detaillierterer Umweltinteraktion. Durch gezielte Verhaltenslogiken und effizientere Rendering-Methoden wird eine realistischere und authentischere Simulation ermöglicht. Weitere Optimierungen und Erweiterungen können hinzugefügt werden, um die Simulation noch weiter zu verfeinern.
Not yet included in a published release.
Vegetation und Nest
Performance Verbesserungen:
Verringern der Anzahl der Zeichnungen: In der aktuellen Version werden alle Voxel gezeichnet, was ineffizient ist. Für eine größere Umgebung sollten Optimierungen wie das Zeichnen nur sichtbarer Voxel eingeführt werden.
Verwendung von NumPy und Vektorisierungen: Wo möglich, nutzen wir NumPy für effiziente Berechnungen.
Benutzerinteraktion:
Zoom Steuerung: Benutzer können die Ansicht durch Tasten für Zoom ändern.
UI-Elemente: Anzeigen von Informationen wie gesammelter Nahrung.