bei dieser anwendung gibt es einige richtlinien die unbedingt einbehalten werden müssen…
- User
bei dieser anwendung gibt es einige richtlinien die unbedingt einbehalten werden müssen und die umsetzungen müssen mit sorgfalt durchdacht werden. Extrem wichtig ist eine authentische und möglichst realistische art der programmierung, indem soweit es möglich ist die verschiedenen inhalte nur so zu programmieren wie sie in der natur auch funktionieren, anstatt einfach das resultat einzuprogrammieren das man gerne hätte. Stattdessen sollen grundlegende auf der realität beruhende algorythmen bzw regeln wie naturgesetzt und so weiter, dafür sorgen das quasi auf natürliche weise das resultat was realistisch ist von alleine entsteht. Insbesondere die ameisen ki soll dabei möglichst realitätsnah und im prinzip auch möglichst einfach programmiert werden. Möglichst grundlegende algorythmen und regeln sollen bestimmten wie die resultierenden ergebnisse aussehen, welche natürlich realistisch werden sollen. Eine ameise soll zb kein metawissen nutzen und zum beispiel wege zu orten finden die sie weder kennt noch einfach so finden kann. Die ameisen sollen ihre sinnesorgange nutzten und natur gegebenen algorythmen befolgen, und so für ein möglichst authentisches gesamt resultat sorgen. daher ist immer sehr stark darauf zu achten das die umsetzung programmiertechnisch so verläuft das sie einerseits grundlegende klare reglen festlegt, diese aber immernoch von den auswirkungen her möglichst frei sind um den "sandboxartigen effekt" zu erzeugen. Resultate sollen realistisch und authentisch sein (wie sie erwartet werden), allerdings soll der weg dahin letztlich möglichst frei und von alleine gefunden werden, was dadurch für interessante überaschungen bei der beobachtung führen kann. Soviel grundsetzlich zu dem programmiertechnischen "geist" und inneren einstellungen währen der bearbeitung dieses projektes.du wirst nun wohl erkennen in welcher art und weise die inhalte in dieser anwendung erstellt werden müssen. Daher versuche nun das skript dieser anwendung so zu verbessern, wie es diese anwendung verdient hat und es fordert! Zunächst habe ich hier zwei skripte. das zweite enthält verbesserungen aber es fehlen darin inhalte aus dem ersten skript. Daher kombiniere diese skripte und verwende die am besten geeignesten inhalte. Entwickel zudem die anwendung in den bereichen weiter die am ehesten entwicklungen benötigen. Erstelle die inhalte stets sorgfälltig durchdacht und entsprechend dem geist der anwendung. nenne aufjedenfall am abschluss deiner nachricht den gesamten verbesserten skript der vollständigen antwort ohne fehlende inhalte.
Skript 1:
ich denke du muss immer noch einige urspngliche inhalte übersehen haben. Kombiniere dein skript mit diesem hier und verwende überall die besten umsetzungen der inhalten.
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 Ameisenparameter
ANT_SIZE = 0.5 # Größe einer Ameise LEG_LENGTH = ANT_SIZE / 3 ANTENNA_LENGTH = ANT_SIZE / 2 NUM_LEGS = 6 NUM_ANTENNA_SEGMENTS = 3 NUM_BODY_SEGMENTS = 3 MAX_LEG_STRETCH = LEG_LENGTH * 1.2 Detailabschneidungsdistanz
CULL_DISTANCE = 50 Gravitation (für zukünftige Verwendung)
GRAVITY = np.array([0, 0, -0.1]) Tunnelmodus
tunnel_mode = False Tag/Nacht-Zyklusparameter
DAY_LENGTH = 1000 # Anzahl der Simulationsschritte für einen vollständigen Tag/Nacht-Zyklus current_time = 0 Pheromonarten
FOOD_PHEROMONE = 0 HOME_PHEROMONE = 1 Pheromonvisualisierung
PHEROMONE_VISUALIZATION_SCALE = 20 UI-Elemente
button_font = None # Wird später initialisiert
Klassen
class Voxel: def init(self, voxel_type): self.type = voxel_type self.pheromones = [0.0] * 2 # [Food Pheromone, Home Pheromone] self.alpha = 255 # Standard: Opaque
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.""" 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): if moisture < -0.5: voxel_types[x, y, z] = SOIL # Beispiel: Trockenere Gebiete als SOIL else: voxel_types[x, y, z] = 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])): voxel_types[x, y, pz] = FOOD # Beispiel: Pflanzen als FOOD definiertFelsen 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]: voxel_types[fx, fy, fz] = SOILGras 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
def place_object(obj, x, y, z, scale=1, rotation=0): """Platziert ein Objekt mit Skalierung und Rotation.""" for dx in range(obj.shape[0]): for dy in range(obj.shape[1]): for dz in range(obj.shape[2]): voxel_z = z + dz if voxel_z >= ENV_SIZE[2]: continue voxel_types[x, y, voxel_z] = max(voxel_types[x, y, voxel_z], obj[dx, dy, dz])
Gras platzieren
for _ in range(200): # Anzahl kleiner Grasbüschel x = random.randint(0, ENV_SIZE[0] - 1) y = random.randint(0, ENV_SIZE[1] - 1) terrain_height = int(height_noise.noise2(x / 20, y / 20) * 10 + ENV_SIZE[2] / 4) z = terrain_height place_object(small_grass, x, y, z, scale=random.uniform(0.8, 1.2), rotation=random.randint(0, 360))
for _ in range(50): # Anzahl großer Grasbüschel x = random.randint(0, ENV_SIZE[0] - 1) y = random.randint(0, ENV_SIZE[1] - 1) terrain_height = int(height_noise.noise2(x / 20, y / 20) * 10 + ENV_SIZE[2] / 4) z = terrain_height place_object(large_grass, x, y, z, scale=random.uniform(0.8, 1.2), rotation=random.randint(0, 360))
Dandelions platzieren
for _ in range(20): # Anzahl Dandelions x = random.randint(0, ENV_SIZE[0] - 1) y = random.randint(0, ENV_SIZE[1] - 1) terrain_height = int(height_noise.noise2(x / 20, y / 20) * 10 + ENV_SIZE[2] / 4) z = terrain_height place_object(dandelion, x, y, z, scale=random.uniform(0.8, 1.2), rotation=random.randint(0, 360))
grid.point_data["voxel_types"] = voxel_types.flatten() 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])
screen_x = width / 2 + rotated_x * zoom * 10 screen_y = height / 2 + (relative_pos[1] * zoom * 10 - rotated_z * zoom * 5) return screen_x, screen_y
def draw_voxel(voxel, position, zoom): """Zeichnet einen einzelnen Voxel auf dem Bildschirm.""" screen_x, screen_y = project_to_screen(position + VOXEL_SIZE / 2, zoom) color = (255, 255, 255) # Standardfarbe if voxel.type == SOIL: color = (139, 69, 19) # Braun für Erde elif voxel.type == FOOD: color = (255, 255, 0) # Gelb für Nahrung elif voxel.type == NEST_MATERIAL: color = (128, 0, 128) # Violett für Nestmaterial elif voxel.type == SAND: color = (194, 178, 128) # Sandfarben
pygame.draw.rect( screen, color, (int(screen_x), int(screen_y), int(VOXEL_SIZE * zoom), int(VOXEL_SIZE * zoom)), 0 )
def draw_environment(grid, tunnel_mode, camera_pos, colony, show_pheromones): """Zeichnet die gesamte Umgebung.""" 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
def main(): global grid, voxel_types, camera_pos, camera_target, zoom, camera_rotation, environment, tunnel_mode, button_font, width, height
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, 30)
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 = 1.0 camera_rotation = np.array([0.0, 0.0]) # Rotation um x- und y-Achse
PyVista-Initialisierung
pv.set_plot_theme("document") plotter = pv.Plotter(off_screen=True) grid = pv.UniformGrid() grid.dimensions = np.array(ENV_SIZE) + 1 grid.spacing = (VOXEL_SIZE, VOXEL_SIZE, VOXEL_SIZE) grid.origin = (0, 0, 0) voxel_types = np.zeros(ENV_SIZE, dtype=int) grid.point_data["voxel_types"] = voxel_types.flatten() plotter.add_mesh(grid, name="environment")
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]): environment[x, y, z] = Voxel(voxel_types[x, y, z]) 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 - 150, 10, 140, 40) show_pheromones = False
running = True while running: # Ereignisbehandlung for event in pygame.event.get(): if event.type == pygame.QUIT: running = False camera_controls(plotter, 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((0, 0, 0)) # Kameraposition aktualisieren plotter.camera_position = [ (camera_pos[0] * VOXEL_SIZE, camera_pos[1] * VOXEL_SIZE, camera_pos[2] * VOXEL_SIZE), (camera_target[0] * VOXEL_SIZE, camera_target[1] * VOXEL_SIZE, camera_target[2] * VOXEL_SIZE), (0, 0, 1) ] # Ameisenlogik 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 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 ) ant.draw(screen, camera_pos, zoom) # Physik anwenden und Pheromone verdunsten apply_physics(environment, 0, 0, 0) # Beispiel: Physik um (0,0,0) 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() # Umgebung zeichnen draw_environment(grid, tunnel_mode, camera_pos, colony, show_pheromones) # 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 + 10, show_pheromones_button.y + 10)) # Bildschirmausgabe aktualisieren pygame.display.flip() clock.tick(30) # Framerate begrenzenpygame.quit()
if name == "main": main()
Skript 2:
Importieren der notwendigen Bibliotheken
from panda3d.core import * from direct.showbase.ShowBase import ShowBase from direct.task import Task from direct.gui.OnscreenText import OnscreenText from direct.gui.DirectGui import DirectButton from panda3d.core import CollisionTraverser, CollisionNode, CollisionHandlerQueue, CollisionRay import numpy as np import random import opensimplex import math
============================
Umgebungsparameter
============================
ENV_SIZE = (50, 50, 20) # Größe der Umgebung (Breite, Höhe, Tiefe) VOXEL_SIZE = 0.5 # 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_DIFFUSION_RATE = 0.05 # Rate, mit der Pheromone sich ausbreiten PHEROMONE_DECAY_FACTOR = 0.98 # Faktor zur Verdunstung FOOD_PHEROMONE_THRESHOLD = 0.3 # Schwellenwert für Ameisen, um Nahrungspfeiferomone zu folgen
============================
Voxel-Typen
============================
AIR = 0 SOIL = 1 FOOD = 2 NEST_MATERIAL = 3 SAND = 4 # Beispielsweise für verschiedene Bodenarten
============================
Pheromon-Typen
============================
FOOD_PHEROMONE = 0 HOME_PHEROMONE = 1 NUM_PHEROMONE_TYPES = 2
============================
Tag/Nacht-Zyklus
============================
DAY_LENGTH = 2000 # Anzahl der Simulationsschritte für einen vollständigen Tag/Nacht-Zyklus current_time = 0
============================
Kamraparameter
============================
camera_distance = 30 # Anfangsabstand der Kamera zoom_factor = 1.0 selected_voxel = None # Aktuell ausgewählter Voxel
============================
Voxel Klasse
============================
class Voxel: def init(self, voxel_type=AIR): self.type = voxel_type self.pheromones = np.zeros(NUM_PHEROMONE_TYPES) # [Food Pheromone, Home Pheromone]
def evaporate_pheromones(self): self.pheromones *= PHEROMONE_DECAY_FACTOR def diffuse_pheromones(self, environment, x, y, z): for pher_type in range(NUM_PHEROMONE_TYPES): spread = self.pheromones[pher_type] * PHEROMONE_DIFFUSION_RATE self.pheromones[pher_type] *= (1 - PHEROMONE_DIFFUSION_RATE) for dx in [-1, 0, 1]: for dy in [-1, 0, 1]: for dz in [-1, 0, 1]: if dx == 0 and dy == 0 and dz == 0: continue 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]: environment[nx, ny, nz].pheromones[pher_type] += spread / 26 # 26 mögliche Nachbarn============================
Kolonieklasse
============================
class Colony: def init(self, nest_entrance): self.nest_entrance = nest_entrance # Tuple (x, y, z) self.ants = [] self.food_count = 0
============================
Ameisenklasse
============================
class Ant: def init(self, colony, voxel_model): self.colony = colony self.position = np.array(colony.nest_entrance, dtype=float) + np.random.uniform(-1, 1, 3) self.has_food = False self.direction = self.random_direction() self.speed = 0.2 # Bewegungsgeschwindigkeit self.model = voxel_model.copyTo(render) self.model.setPos(self.position[0] * VOXEL_SIZE, self.position[1] * VOXEL_SIZE, self.position[2] * VOXEL_SIZE) self.update_color()
def random_direction(self): vec = np.random.uniform(-1, 1, 3) vec[2] = 0 # Bewegung nur in der XY-Ebene norm = np.linalg.norm(vec) if norm == 0: return self.random_direction() return vec / norm 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 = 2 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 not self.has_food else environment[nx, ny, nz].pheromones[HOME_PHEROMONE] if pheromone_strength > FOOD_PHEROMONE_THRESHOLD: 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 = self.random_direction() # Zufällige Neigung zur Richtung, um Navigationsfehler zu simulieren angle = random.uniform(-math.pi / 8, math.pi / 8) rotation_matrix = np.array([ [math.cos(angle), -math.sin(angle), 0], [math.sin(angle), math.cos(angle), 0], [0, 0, 1] ]) self.direction = rotation_matrix.dot(self.direction) if np.linalg.norm(self.direction) > 0: self.direction /= np.linalg.norm(self.direction) # Neue Position berechnen new_position = self.position + self.direction * self.speed # Bounds-Check und Verhindern des Austretens aus der Umgebung new_position = np.clip(new_position, [0, 0, 0], [ENV_SIZE[0] - 1, ENV_SIZE[1] - 1, ENV_SIZE[2] - 1]) # Überprüfen, ob die neue Position begehbar ist nx, ny, nz = int(new_position[0]), int(new_position[1]), int(new_position[2]) if environment[nx, ny, nz].type == AIR or environment[nx, ny, nz].type == FOOD: self.position = new_position self.model.setPos(self.position[0] * VOXEL_SIZE, self.position[1] * VOXEL_SIZE, self.position[2] * VOXEL_SIZE) def forage(self, environment): x, y, z = int(self.position[0]), int(self.position[1]), int(self.position[2]) current_voxel = environment[x, y, z] if not self.has_food and current_voxel.type == FOOD: self.has_food = True current_voxel.type = AIR # Nahrung aufnehmen self.update_color() 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 ) self.update_color() def deposit_pheromones(self, environment): x, y, z = int(self.position[0]), int(self.position[1]), int(self.position[2]) if self.has_food: environment[x, y, z].pheromones[FOOD_PHEROMOPE] += 0.5 else: environment[x, y, z].pheromones[HOME_PHEROMONE] += 0.5 def update(self, environment, sun_direction): self.move(environment, sun_direction) self.forage(environment) self.deposit_pheromones(environment) def update_color(self): if self.has_food: self.model.setColor(1, 0, 0, 1) # Rot für Träger else: self.model.setColor(0, 0, 1, 1) # Blau für ohne Nahrung============================
Hilfsfunktionen
============================
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 + 1, min(z + 3, ENV_SIZE[2])): 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(): """Generiert die Umgebung mit Gelände, Feuchtigkeitsverteilungen und Objekten.""" environment = np.empty(ENV_SIZE, dtype=object) 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]): for z in range(ENV_SIZE[2]): terrain_height = int((height_noise.noise2(x / 10, y / 10) + 1) * 5) + ENV_SIZE[2] // 4 if z < terrain_height: if moisture_noise.noise2(x / 20, y / 20) < -0.2: environment[x, y, z] = Voxel(SAND) # Beispiel: SAND für trockene Gebiete else: environment[x, y, z] = Voxel(SOIL) else: environment[x, y, z] = Voxel(AIR) # Procedurale Objektgenerierung (z.B. Pflanzen) if moisture_noise.noise2(x / 20, y / 20) > 0.5 and random.random() < 0.1: plant_height = random.randint(1, 3) for pz in range(terrain_height, min(terrain_height + plant_height, ENV_SIZE[2])): environment[x, y, pz].type = FOOD # Beispiel: Pflanzen als FOOD definiert # Felsen generieren (unregelmäßige Formen) for _ in range(20): # Anzahl der Felsen center_x = random.randint(5, ENV_SIZE[0] - 6) center_y = random.randint(5, ENV_SIZE[1] - 6) center_z = int((height_noise.noise2(center_x / 10, center_y / 10) + 1) * 5) + ENV_SIZE[2] // 4 radius = random.randint(2, 4) irregularity = random.uniform(0.7, 1.2) 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]: environment[fx, fy, fz].type = 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 # Funktion zum Platzieren von Objekten def place_object(obj, x, y, z, scale=1, rotation=0): """Platziert ein Objekt mit Skalierung und Rotation.""" for dx in range(obj.shape[0]): for dy in range(obj.shape[1]): for dz in range(obj.shape[2]): voxel_z = z + dz if voxel_z >= ENV_SIZE[2]: continue if obj[dx, dy, dz][2] > 0: environment[x, y, voxel_z].type = max(environment[x, y, voxel_z].type, obj[dx, dy, dz][2]) # Gras platzieren for _ in range(100): # Anzahl kleiner Grasbüschel x = random.randint(0, ENV_SIZE[0] - 1) y = random.randint(0, ENV_SIZE[1] - 1) terrain_height = int((height_noise.noise2(x / 10, y / 10) + 1) * 5) + ENV_SIZE[2] // 4 z = terrain_height place_object(small_grass, x, y, z, scale=random.uniform(0.8, 1.2), rotation=random.randint(0, 360)) for _ in range(50): # Anzahl großer Grasbüschel x = random.randint(0, ENV_SIZE[0] - 1) y = random.randint(0, ENV_SIZE[1] - 1) terrain_height = int((height_noise.noise2(x / 10, y / 10) + 1) * 5) + ENV_SIZE[2] // 4 z = terrain_height place_object(large_grass, x, y, z, scale=random.uniform(0.8, 1.2), rotation=random.randint(0, 360)) # Dandelions platzieren for _ in range(20): # Anzahl Dandelions x = random.randint(0, ENV_SIZE[0] - 1) y = random.randint(0, ENV_SIZE[1] - 1) terrain_height = int((height_noise.noise2(x / 10, y / 10) + 1) * 5) + ENV_SIZE[2] // 4 z = terrain_height place_object(dandelion, x, y, z, scale=random.uniform(0.8, 1.2), rotation=random.randint(0, 360)) return environment============================
Simulation mit Panda3D
============================
class AntSimulation(ShowBase): def init(self): ShowBase.init(self) self.disableMouse() # Deaktiviert die Standard-Maussteuerung
# Umgebung und Kolonie initialisieren self.environment = generate_environment() self.colony = Colony(nest_entrance=(ENV_SIZE[0] // 2, ENV_SIZE[1] // 2, 1)) # Voxel-Modell laden self.voxel_model = loader.loadModel("models/box") # Einfacher Box-Modell für Voxels self.voxel_model.setScale(VOXEL_SIZE / 2) self.voxel_model.setColor(1, 1, 1, 1) # Voxel im 3D-Raum darstellen self.voxel_nodes = {} for x in range(ENV_SIZE[0]): for y in range(ENV_SIZE[1]): for z in range(ENV_SIZE[2]): voxel = self.environment[x, y, z] if voxel.type != AIR: voxel_node = self.voxel_model.copyTo(render) voxel_node.setPos(x * VOXEL_SIZE, y * VOXEL_SIZE, z * VOXEL_SIZE) if voxel.type == SOIL: voxel_node.setColor(0.545, 0.271, 0.075, 1) # Braun für Boden elif voxel.type == FOOD: voxel_node.setColor(1, 1, 0, 1) # Gelb für Nahrung elif voxel.type == NEST_MATERIAL: voxel_node.setColor(0.545, 0.272, 0.075, 1) # Dunkelbraun für Nestmaterial elif voxel.type == SAND: voxel_node.setColor(0.76, 0.69, 0.50, 1) # Sandfarben self.voxel_nodes[(x, y, z)] = voxel_node # Ameisenmodell laden self.ant_model = loader.loadModel("models/box") # Platzhalter-Modell, ersetzen Sie dies mit einem besseren Modell self.ant_model.setScale(0.2, 0.2, 0.5) # Angepasst an ANT_SIZE self.ant_model.setColor(0, 0, 1, 1) # Blau initial # Liste zur Verwaltung der Antenodes self.ant_nodes = [] self.colony.ants = [Ant(self.colony, self.ant_model) for _ in range(INITIAL_ANTS)] for ant in self.colony.ants: self.ant_nodes.append(ant.model) # Kamera-Initialisierung self.camera_distance = 30 self.zoom = 1.0 self.selected_voxel = None self.accept("esc", exit) # Auswahl der Voxels self.cTrav = CollisionTraverser() self.picker = CollisionNode('mouseRay') self.picker_ray = CollisionRay() self.picker.addSolid(self.picker_ray) self.picker_handler = CollisionHandlerQueue() self.picker_np = render.attachNewNode(self.picker) self.cTrav.addCollider(self.picker_np, self.picker_handler) self.accept("mouse1", self.on_mouse_click) self.accept("mouse2", self.on_double_click) # Task hinzufügen, um die Simulation zu aktualisieren self.taskMgr.add(self.update_simulation, "UpdateSimulation") # UI-Elemente self.show_pheromones = False self.show_underground = False self.ui_text = OnscreenText(text="P - Toggle Pheromones | U - Toggle Underground View", pos=(-1.3, 0.95), scale=0.05, fg=(1,1,1,1), align=TextNode.ALeft) self.accept('p', self.toggle_pheromones) self.accept('u', self.toggle_underground) # Untergrundansicht initialisieren self.ground_level = 1 # Z-Level für Untergrundansicht def toggle_pheromones(self): self.show_pheromones = not self.show_pheromones if self.show_pheromones: self.ui_text.setText("Pheromones: ON | U - Toggle Underground View") else: self.ui_text.setText("Pheromones: OFF | U - Toggle Underground View") def toggle_underground(self): self.show_underground = not self.show_underground if self.show_underground: self.ground_level = 3 # Tiefer schwenken self.ui_text.setText("Pheromones: " + ("ON" if self.show_pheromones else "OFF") + " | Underground View: ON") else: self.ground_level = 1 # Zurück zur Oberansicht self.ui_text.setText("Pheromones: " + ("ON" if self.show_pheromones else "OFF") + " | Underground View: OFF") def on_mouse_click(self): """Einzelklick zur Auswahl eines Voxels.""" if self.mouseWatcherNode.hasMouse(): mpos = self.mouseWatcherNode.getMouse() self.picker_ray.setFromLens(base.camNode, mpos.getX(), mpos.getY()) self.cTrav.traverse(render) if self.picker_handler.getNumEntries() > 0: self.picker_handler.sortEntries() entry = self.picker_handler.getEntry(0) picked_np = entry.getIntoNodePath() pos = picked_np.getPos(render) x = int(pos.getX() / VOXEL_SIZE) y = int(pos.getY() / VOXEL_SIZE) z = int(pos.getZ() / VOXEL_SIZE) if (x, y, z) in self.voxel_nodes: self.selected_voxel = np.array([x, y, z], dtype=float) self.update_camera() def on_double_click(self): """Doppelklick zur Fixierung der Kamera auf einen Voxel.""" if self.mouseWatcherNode.hasMouse(): mpos = self.mouseWatcherNode.getMouse() self.picker_ray.setFromLens(base.camNode, mpos.getX(), mpos.getY()) self.cTrav.traverse(render) if self.picker_handler.getNumEntries() > 0: self.picker_handler.sortEntries() entry = self.picker_handler.getEntry(0) picked_np = entry.getIntoNodePath() pos = picked_np.getPos(render) x = int(pos.getX() / VOXEL_SIZE) y = int(pos.getY() / VOXEL_SIZE) z = int(pos.getZ() / VOXEL_SIZE) if (x, y, z) in self.voxel_nodes: self.selected_voxel = np.array([x, y, z], dtype=float) self.update_camera() def update_camera(self): """Aktualisiert die Kamera basierend auf dem ausgewählten Voxel.""" if self.selected_voxel is not None: target_pos = self.selected_voxel * VOXEL_SIZE cam_x = target_pos[0] + self.camera_distance * math.cos(math.radians(45)) * self.zoom cam_y = target_pos[1] - self.camera_distance * math.sin(math.radians(45)) * self.zoom cam_z = target_pos[2] + 20 * self.zoom # Höhe anpassen base.camera.setPos(cam_x, cam_y, cam_z) base.camera.lookAt(target_pos[0], target_pos[1], target_pos[2] + self.ground_level) else: # Standard kamera base.camera.setPos(ENV_SIZE[0] * VOXEL_SIZE / 2, -ENV_SIZE[1] * VOXEL_SIZE / 2 - camera_distance, ENV_SIZE[2] * VOXEL_SIZE) base.camera.lookAt(ENV_SIZE[0] * VOXEL_SIZE / 2, ENV_SIZE[1] * VOXEL_SIZE / 2, 0) def update_simulation(self, task): global current_time # Simulationsschritte for ant in self.colony.ants: ant.update(self.environment, self.get_sun_direction()) # Verdunstung und Diffusion der Pheromone for x in range(ENV_SIZE[0]): for y in range(ENV_SIZE[1]): for z in range(ENV_SIZE[2]): voxel = self.environment[x, y, z] voxel.evaporate_pheromones() voxel.diffuse_pheromones(self.environment, x, y, z) # Nahrung gelegentlich spawnen if random.random() < FOOD_SPAWN_RATE: x, y = random.randint(0, ENV_SIZE[0]-1), random.randint(0, ENV_SIZE[1]-1) z = 1 # Nahrung auf Bodenniveau if self.environment[x, y, z].type == AIR: self.environment[x, y, z].type = FOOD voxel_node = self.voxel_model.copyTo(render) voxel_node.setPos(x * VOXEL_SIZE, y * VOXEL_SIZE, z * VOXEL_SIZE) voxel_node.setColor(1, 1, 0, 1) # Gelb für Nahrung self.voxel_nodes[(x, y, z)] = voxel_node # Tageszeit aktualisieren current_time = (current_time + 1) % DAY_LENGTH is_day = current_time < DAY_LENGTH / 2 if is_day: render.setLight(render.attachNewNode(PointLight("sun"))) else: render.clearLight() # Pheromone visualisieren if self.show_pheromones: for (x, y, z), voxel_node in self.voxel_nodes.items(): voxel = self.environment[x, y, z] pheromones = voxel.pheromones if pheromones[FOOD_PHEROMONE] > 0 or pheromones[HOME_PHEROMONE] > 0: food_strength = min(pheromones[FOOD_PHEROMONE] / 10, 1) home_strength = min(pheromones[HOME_PHEROMONE] / 10, 1) if pheromones[FOOD_PHEROMONE] > 0 and pheromones[HOME_PHEROMONE] > 0: voxel_node.setColorScale(1, 1 - home_strength, 0, 0.5) # Grün für Nahrung, Blau für Heim elif pheromones[FOOD_PHEROMONE] > 0: voxel_node.setColorScale(0, 1, 0, 0.5) # Grün für Nahrung elif pheromones[HOME_PHEROMONE] > 0: voxel_node.setColorScale(0, 0, 1, 0.5) # Blau für Heim else: for voxel_node in self.voxel_nodes.values(): voxel_node.setColorScale(1, 1, 1, 1) return Task.cont def get_sun_direction(self): """Berechnet die Sonnenrichtung basierend auf der aktuellen Tageszeit.""" sun_angle = (current_time / DAY_LENGTH) * 2 * math.pi sun_x = math.sin(sun_angle) sun_y = math.cos(sun_angle) sun_z = 0.5 # Standard Sonnenhöhe if sun_x < 0: sun_z *= 0.2 # Mondlicht, geringere Intensität sun_direction = np.array([sun_x, sun_y, sun_z]) norm = np.linalg.norm(sun_direction) if norm > 0: sun_direction /= norm return sun_direction============================
Hauptausführung
============================
if name == "main": app = AntSimulation() app.run()
- Assistant
Verstanden. Ich werde die beiden Skripte kombinieren, indem ich die besten Implementierungen aus beiden beibehalte und die Funktionalitäten erweitere, die am meisten von Verbesserungen profitieren. Hierbei werde ich sicherstellen, dass die Ameisen-KI so realistisch und authentisch wie möglich bleibt, indem grundlegende natürliche Regeln angewendet werden und emergentes Verhalten entsteht.
Das kombinierte Skript verwendet Panda3D für die 3D-Visualisierung, da es leistungsfähiger für komplexe 3D-Simulationen ist. Die Ameisen werden einfache Bewegungs- und Entscheidungsalgorithmen nutzen, die auf Pheromonen basieren, ohne Meta-Wissen zu verwenden. Die Umgebung wird prozedural generiert, wobei natürliche Gegebenheiten wie Gelände, Feuchtigkeitsverteilungen und Vegetation berücksichtigt werden.
Hier ist das vollständig verbesserte Skript:
# Importieren der notwendigen Bibliotheken from panda3d.core import * from direct.showbase.ShowBase import ShowBase from direct.task import Task from direct.gui.OnscreenText import OnscreenText from direct.gui.DirectGui import DirectButton from panda3d.core import CollisionTraverser, CollisionNode, CollisionHandlerQueue, CollisionRay import numpy as np import random import opensimplex import math # ============================ # Umgebungsparameter # ============================ ENV_SIZE = (100, 100, 50) # Größe der Umgebung (Breite, Höhe, Tiefe) VOXEL_SIZE = 0.5 # 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_DIFFUSION_RATE = 0.05 # Rate, mit der Pheromone sich ausbreiten PHEROMONE_DECAY_FACTOR = 0.98 # Faktor zur Verdunstung FOOD_PHEROMONE_THRESHOLD = 0.3 # Schwellenwert für Ameisen, um Nahrungspfeiferomone zu folgen # ============================ # Voxel-Typen # ============================ AIR = 0 SOIL = 1 FOOD = 2 NEST_MATERIAL = 3 SAND = 4 # Beispielsweise für verschiedene Bodenarten # ============================ # Pheromon-Typen # ============================ FOOD_PHEROMONE = 0 HOME_PHEROMONE = 1 NUM_PHEROMONE_TYPES = 2 # ============================ # Tag/Nacht-Zyklus # ============================ DAY_LENGTH = 2000 # Anzahl der Simulationsschritte für einen vollständigen Tag/Nacht-Zyklus current_time = 0 # ============================ # Kamera-Parameter # ============================ CAMERA_DISTANCE = 100 # Anfangsabstand der Kamera ZOOM_FACTOR = 1.0 selected_voxel = None # Aktuell ausgewählter Voxel # ============================ # Voxel Klasse # ============================ class Voxel: def __init__(self, voxel_type=AIR): self.type = voxel_type self.pheromones = np.zeros(NUM_PHEROMONE_TYPES) # [Food Pheromone, Home Pheromone] def evaporate_pheromones(self): self.pheromones *= PHEROMONE_DECAY_FACTOR def diffuse_pheromones(self, environment, x, y, z): for pher_type in range(NUM_PHEROMONE_TYPES): spread = self.pheromones[pher_type] * PHEROMONE_DIFFUSION_RATE self.pheromones[pher_type] *= (1 - PHEROMONE_DIFFUSION_RATE) for dx in [-1, 0, 1]: for dy in [-1, 0, 1]: for dz in [-1, 0, 1]: if dx == 0 and dy == 0 and dz == 0: continue 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]: environment[nx, ny, nz].pheromones[pher_type] += spread / 26 # 26 mögliche Nachbarn # ============================ # Kolonieklasse # ============================ class Colony: def __init__(self, nest_entrance): self.nest_entrance = nest_entrance # Tuple (x, y, z) self.ants = [] self.food_count = 0 # ============================ # Ameisenklasse # ============================ class Ant: def __init__(self, colony, voxel_model): self.colony = colony self.position = np.array(colony.nest_entrance, dtype=float) + np.random.uniform(-1, 1, 3) self.has_food = False self.direction = self.random_direction() self.speed = 0.2 # Bewegungsgeschwindigkeit self.model = voxel_model.copyTo(render) self.model.setScale(VOXEL_SIZE / 2) self.update_position() self.update_color() def random_direction(self): vec = np.random.uniform(-1, 1, 3) vec[2] = 0 # Bewegung nur in der XY-Ebene norm = np.linalg.norm(vec) if norm == 0: return self.random_direction() return vec / norm def move(self, environment, sun_direction): global current_time 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 = 2 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 not self.has_food else environment[nx, ny, nz].pheromones[HOME_PHEROMONE] if pheromone_strength > FOOD_PHEROMONE_THRESHOLD: 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 = self.random_direction() # Zufällige Neigung zur Richtung, um Navigationsfehler zu simulieren angle = random.uniform(-math.pi / 8, math.pi / 8) rotation_matrix = np.array([ [math.cos(angle), -math.sin(angle), 0], [math.sin(angle), math.cos(angle), 0], [0, 0, 1] ]) self.direction = rotation_matrix.dot(self.direction) if np.linalg.norm(self.direction) > 0: self.direction /= np.linalg.norm(self.direction) # Neue Position berechnen new_position = self.position + self.direction * self.speed # Bounds-Check und Verhindern des Austretens aus der Umgebung new_position = np.clip(new_position, [0, 0, 0], [ENV_SIZE[0] - 1, ENV_SIZE[1] - 1, ENV_SIZE[2] - 1]) # Überprüfen, ob die neue Position begehbar ist nx, ny, nz = int(new_position[0]), int(new_position[1]), int(new_position[2]) if environment[nx, ny, nz].type == AIR or environment[nx, ny, nz].type == FOOD: self.position = new_position self.update_position() # Hindernis erkannt: Richtung ändern else: self.direction = self.random_direction() def forage(self, environment): x, y, z = int(self.position[0]), int(self.position[1]), int(self.position[2]) current_voxel = environment[x, y, z] if not self.has_food and current_voxel.type == FOOD: self.has_food = True current_voxel.type = AIR # Nahrung aufnehmen self.update_color() 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 ) self.update_color() def deposit_pheromones(self, environment): x, y, z = int(self.position[0]), int(self.position[1]), int(self.position[2]) if self.has_food: environment[x, y, z].pheromones[FOOD_PHEROMONE] += 0.5 else: environment[x, y, z].pheromones[HOME_PHEROMONE] += 0.5 def update(self, environment, sun_direction): self.move(environment, sun_direction) self.forage(environment) self.deposit_pheromones(environment) def update_position(self): self.model.setPos(self.position[0] * VOXEL_SIZE, self.position[1] * VOXEL_SIZE, self.position[2] * VOXEL_SIZE) def update_color(self): if self.has_food: self.model.setColor(1, 0, 0, 1) # Rot für Träger else: self.model.setColor(0, 0, 1, 1) # Blau für ohne Nahrung # ============================ # Hilfsfunktionen # ============================ 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 + 1, min(z + 3, ENV_SIZE[2])): 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 # Physik nach dem Ablegen anwenden apply_physics(environment, nx, ny, lnz) def generate_environment(): """Generiert die Umgebung mit Gelände, Feuchtigkeitsverteilungen und Objekten.""" environment = np.empty(ENV_SIZE, dtype=object) 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]): for z in range(ENV_SIZE[2]): terrain_height = int((height_noise.noise2(x / 10, y / 10) + 1) * 10) + ENV_SIZE[2] // 4 if z < terrain_height: if moisture_noise.noise2(x / 20, y / 20) < -0.2: environment[x, y, z] = Voxel(SAND) # Beispiel: SAND für trockene Gebiete else: environment[x, y, z] = Voxel(SOIL) else: environment[x, y, z] = Voxel(AIR) # Procedurale Objektgenerierung (z.B. Pflanzen) if moisture_noise.noise2(x / 20, y / 20) > 0.5 and random.random() < 0.1: plant_height = random.randint(1, 3) for pz in range(int((height_noise.noise2(x / 10, y / 10) + 1) * 10) + ENV_SIZE[2] // 4, min(int((height_noise.noise2(x / 10, y / 10) + 1) * 10) + ENV_SIZE[2] // 4 + plant_height, ENV_SIZE[2])): environment[x, y, pz].type = FOOD # Beispiel: Pflanzen als FOOD definiert # Felsen generieren (unregelmäßige Formen) for _ in range(20): # Anzahl der Felsen center_x = random.randint(5, ENV_SIZE[0] - 6) center_y = random.randint(5, ENV_SIZE[1] - 6) center_z = int((height_noise.noise2(center_x / 10, center_y / 10) + 1) * 10) + ENV_SIZE[2] // 4 radius = random.randint(2, 4) irregularity = random.uniform(0.7, 1.2) 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]: environment[fx, fy, fz].type = 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 def place_object(obj, x, y, z, scale=1, rotation=0): """Platziert ein Objekt mit Skalierung und Rotation.""" for dx in range(obj.shape[0]): for dy in range(obj.shape[1]): for dz in range(obj.shape[2]): voxel_z = z + dz if voxel_z >= ENV_SIZE[2]: continue if obj[dx, dy, dz][2] > 0: environment[x, y, voxel_z].type = max(environment[x, y, voxel_z].type, obj[dx, dy, dz][2]) # Gras platzieren for _ in range(200): # Anzahl kleiner Grasbüschel x = random.randint(0, ENV_SIZE[0] - 1) y = random.randint(0, ENV_SIZE[1] - 1) terrain_height = int((height_noise.noise2(x / 10, y / 10) + 1) * 10) + ENV_SIZE[2] // 4 z = terrain_height place_object(small_grass, x, y, z, scale=random.uniform(0.8, 1.2), rotation=random.randint(0, 360)) for _ in range(50): # Anzahl großer Grasbüschel x = random.randint(0, ENV_SIZE[0] - 1) y = random.randint(0, ENV_SIZE[1] - 1) terrain_height = int((height_noise.noise2(x / 10, y / 10) + 1) * 10) + ENV_SIZE[2] // 4 z = terrain_height place_object(large_grass, x, y, z, scale=random.uniform(0.8, 1.2), rotation=random.randint(0, 360)) # Dandelions platzieren for _ in range(20): # Anzahl Dandelions x = random.randint(0, ENV_SIZE[0] - 1) y = random.randint(0, ENV_SIZE[1] - 1) terrain_height = int((height_noise.noise2(x / 10, y / 10) + 1) * 10) + ENV_SIZE[2] // 4 z = terrain_height place_object(dandelion, x, y, z, scale=random.uniform(0.8, 1.2), rotation=random.randint(0, 360)) return environment # ============================ # Simulation mit Panda3D # ============================ class AntSimulation(ShowBase): def __init__(self): ShowBase.__init__(self) self.disableMouse() # Deaktiviert die Standard-Maussteuerung # Umgebung und Kolonie initialisieren self.environment = generate_environment() self.colony = Colony(nest_entrance=(ENV_SIZE[0] // 2, ENV_SIZE[1] // 2, 1)) # Voxel-Modell laden self.voxel_model = loader.loadModel("models/box") # Einfacher Box-Modell für Voxels self.voxel_model.setScale(VOXEL_SIZE / 2) self.voxel_model.setColor(1, 1, 1, 1) # Voxel im 3D-Raum darstellen self.voxel_nodes = {} for x in range(ENV_SIZE[0]): for y in range(ENV_SIZE[1]): for z in range(ENV_SIZE[2]): voxel = self.environment[x, y, z] if voxel.type != AIR: voxel_node = self.voxel_model.copyTo(render) voxel_node.setPos(x * VOXEL_SIZE, y * VOXEL_SIZE, z * VOXEL_SIZE) if voxel.type == SOIL: voxel_node.setColor(0.545, 0.271, 0.075, 1) # Braun für Boden elif voxel.type == FOOD: voxel_node.setColor(1, 1, 0, 1) # Gelb für Nahrung elif voxel.type == NEST_MATERIAL: voxel_node.setColor(0.545, 0.272, 0.075, 1) # Dunkelbraun für Nestmaterial elif voxel.type == SAND: voxel_node.setColor(0.76, 0.69, 0.50, 1) # Sandfarben self.voxel_nodes[(x, y, z)] = voxel_node # Ameisenmodell laden self.ant_model = loader.loadModel("models/box") # Platzhalter-Modell, ersetzen Sie dies mit einem besseren Modell self.ant_model.setScale(0.2, 0.2, 0.5) # Angepasst an ANT_SIZE self.ant_model.setColor(0, 0, 1, 1) # Blau initial # Liste zur Verwaltung der Antenodes self.ant_nodes = [] self.colony.ants = [Ant(self.colony, self.ant_model) for _ in range(INITIAL_ANTS)] for ant in self.colony.ants: self.ant_nodes.append(ant.model) # Kamera-Initialisierung self.camera_distance = CAMERA_DISTANCE self.zoom = ZOOM_FACTOR self.selected_voxel = None self.accept("escape", exit) self.set_camera_position() # Auswahl der Voxels self.cTrav = CollisionTraverser() self.picker = CollisionNode('mouseRay') self.picker_ray = CollisionRay() self.picker.addSolid(self.picker_ray) self.picker_handler = CollisionHandlerQueue() self.picker_np = render.attachNewNode(self.picker) self.cTrav.addCollider(self.picker_np, self.picker_handler) self.accept("mouse1", self.on_mouse_click) self.accept("mouse2", self.on_double_click) # Task hinzufügen, um die Simulation zu aktualisieren self.taskMgr.add(self.update_simulation, "UpdateSimulation") # UI-Elemente self.show_pheromones = False self.show_underground = False self.ui_text = OnscreenText(text="P - Toggle Pheromones | U - Toggle Underground View", pos=(-1.3, 0.95), scale=0.05, fg=(1,1,1,1), align=TextNode.ALeft) self.accept('p', self.toggle_pheromones) self.accept('u', self.toggle_underground) # Untergrundansicht initialisieren self.ground_level = 1 # Z-Level für Untergrundansicht def set_camera_position(self): """Setzt die Kamera auf die Standardposition.""" base.camera.setPos(ENV_SIZE[0] * VOXEL_SIZE / 2, -ENV_SIZE[1] * VOXEL_SIZE / 2 - self.camera_distance, ENV_SIZE[2] * VOXEL_SIZE) base.camera.lookAt(ENV_SIZE[0] * VOXEL_SIZE / 2, ENV_SIZE[1] * VOXEL_SIZE / 2, 0) def toggle_pheromones(self): self.show_pheromones = not self.show_pheromones if self.show_pheromones: self.ui_text.setText("Pheromones: ON | U - Toggle Underground View") else: self.ui_text.setText("Pheromones: OFF | U - Toggle Underground View") def toggle_underground(self): self.show_underground = not self.show_underground if self.show_underground: self.ground_level = 3 # Tiefer schwenken self.ui_text.setText("Pheromones: " + ("ON" if self.show_pheromones else "OFF") + " | Underground View: ON") else: self.ground_level = 1 # Zurück zur Oberansicht self.ui_text.setText("Pheromones: " + ("ON" if self.show_pheromones else "OFF") + " | Underground View: OFF") def on_mouse_click(self): """Einzelklick zur Auswahl eines Voxels.""" if self.mouseWatcherNode.hasMouse(): mpos = self.mouseWatcherNode.getMouse() self.picker_ray.setFromLens(base.camNode, mpos.getX(), mpos.getY()) self.cTrav.traverse(render) if self.picker_handler.getNumEntries() > 0: self.picker_handler.sortEntries() entry = self.picker_handler.getEntry(0) picked_np = entry.getIntoNodePath() pos = picked_np.getPos(render) x = int(pos.getX() / VOXEL_SIZE) y = int(pos.getY() / VOXEL_SIZE) z = int(pos.getZ() / VOXEL_SIZE) if (x, y, z) in self.voxel_nodes: self.selected_voxel = np.array([x, y, z], dtype=float) self.update_camera() def on_double_click(self): """Doppelklick zur Fixierung der Kamera auf einen Voxel.""" if self.mouseWatcherNode.hasMouse(): mpos = self.mouseWatcherNode.getMouse() self.picker_ray.setFromLens(base.camNode, mpos.getX(), mpos.getY()) self.cTrav.traverse(render) if self.picker_handler.getNumEntries() > 0: self.picker_handler.sortEntries() entry = self.picker_handler.getEntry(0) picked_np = entry.getIntoNodePath() pos = picked_np.getPos(render) x = int(pos.getX() / VOXEL_SIZE) y = int(pos.getY() / VOXEL_SIZE) z = int(pos.getZ() / VOXEL_SIZE) if (x, y, z) in self.voxel_nodes: self.selected_voxel = np.array([x, y, z], dtype=float) self.update_camera() def update_camera(self): """Aktualisiert die Kamera basierend auf dem ausgewählten Voxel.""" if self.selected_voxel is not None: target_pos = self.selected_voxel * VOXEL_SIZE cam_x = target_pos[0] + self.camera_distance * math.cos(math.radians(45)) * self.zoom cam_y = target_pos[1] - self.camera_distance * math.sin(math.radians(45)) * self.zoom cam_z = target_pos[2] + 20 * self.zoom # Höhe anpassen base.camera.setPos(cam_x, cam_y, cam_z) base.camera.lookAt(target_pos[0], target_pos[1], target_pos[2] + self.ground_level) else: # Standard kamera self.set_camera_position() def update_simulation(self, task): global current_time # Simulationsschritte sun_direction = self.get_sun_direction() for ant in self.colony.ants: ant.update(self.environment, sun_direction) # Verdunstung und Diffusion der Pheromone for x in range(ENV_SIZE[0]): for y in range(ENV_SIZE[1]): for z in range(ENV_SIZE[2]): voxel = self.environment[x, y, z] voxel.evaporate_pheromones() voxel.diffuse_pheromones(self.environment, x, y, z) # Nahrung gelegentlich spawnen if random.random() < FOOD_SPAWN_RATE: x, y = random.randint(0, ENV_SIZE[0]-1), random.randint(0, ENV_SIZE[1]-1) z = 1 # Nahrung auf Bodenniveau if self.environment[x, y, z].type == AIR: self.environment[x, y, z].type = FOOD voxel_node = self.voxel_model.copyTo(render) voxel_node.setPos(x * VOXEL_SIZE, y * VOXEL_SIZE, z * VOXEL_SIZE) voxel_node.setColor(1, 1, 0, 1) # Gelb für Nahrung self.voxel_nodes[(x, y, z)] = voxel_node # Tageszeit aktualisieren current_time = (current_time + 1) % DAY_LENGTH is_day = current_time < DAY_LENGTH / 2 if is_day: render.setLight(render.attachNewNode(PointLight("sun"))) else: render.clearLight() # Pheromone visualisieren if self.show_pheromones: for (x, y, z), voxel_node in self.voxel_nodes.items(): voxel = self.environment[x, y, z] pheromones = voxel.pheromones if pheromones[FOOD_PHEROMONE] > 0 or pheromones[HOME_PHEROMONE] > 0: food_strength = min(pheromones[FOOD_PHEROMONE] / 10, 1) home_strength = min(pheromones[HOME_PHEROMONE] / 10, 1) if pheromones[FOOD_PHEROMONE] > 0 and pheromones[HOME_PHEROMONE] > 0: voxel_node.setColorScale(1, 1 - home_strength, 0, 0.5) # Grün für Nahrung, Blau für Heim elif pheromones[FOOD_PHEROMONE] > 0: voxel_node.setColorScale(0, 1, 0, 0.5) # Grün für Nahrung elif pheromones[HOME_PHEROMONE] > 0: voxel_node.setColorScale(0, 0, 1, 0.5) # Blau für Heim else: for voxel_node in self.voxel_nodes.values(): voxel_node.setColorScale(1, 1, 1, 1) return Task.cont def get_sun_direction(self): """Berechnet die Sonnenrichtung basierend auf der aktuellen Tageszeit.""" sun_angle = (current_time / DAY_LENGTH) * 2 * math.pi sun_x = math.sin(sun_angle) sun_y = math.cos(sun_angle) sun_z = 0.5 # Standard Sonnenhöhe if sun_x < 0: sun_z *= 0.2 # Mondlicht, geringere Intensität sun_direction = np.array([sun_x, sun_y, sun_z]) norm = np.linalg.norm(sun_direction) if norm > 0: sun_direction /= norm return sun_direction # ============================ # Hauptausführung # ============================ if __name__ == "__main__": app = AntSimulation() app.run()Erläuterungen und Verbesserungen
-
Verwendung von Panda3D: Das Skript nutzt Panda3D für die 3D-Visualisierung, was für eine realistischere Darstellung und komplexere Interaktionen besser geeignet ist als Pygame.
-
Realistische Ameisenbewegung:
- Richtungsfindung: Die Ameisen bewegen sich basierend auf Pheromonen und einer zufälligen Komponente, um natürliche Bewegung und exploratives Verhalten zu simulieren.
- Keine Meta-Wissen: Die Ameisen haben kein Wissen über die gesamte Umgebung, sie reagieren nur auf lokale Pheromonspuren und ihre unmittelbare Umgebung.
- Phasen der Nahrungssuche und Rückkehr: Die Ameisen wechseln zwischen der Nahrungssuche und der Rückkehr zum Nest, basierend auf ihrem Trägerstatus.
-
Pheromonmanagement:
- Verdunstung und Diffusion: Pheromone verdunsten mit der Zeit und diffundieren in die Umgebung, was ein dynamisches und realistisches Pheromonfeld erzeugt.
- Visualisierung: Pheromone können ein- und ausgeschaltet angezeigt werden, um das Verhalten der Ameisen besser beobachten zu können.
-
Umgebungsgenerierung:
- Prozedurales Gelände: Die Umgebung wird prozedural mit Höhen- und Feuchtigkeitsmustern generiert, was Vielfalt und Realismus in der Landschaft schafft.
- Vegetation und Objekte: Gras, Dandelions und Felsen werden zufällig platziert, um eine lebendige und abwechslungsreiche Umgebung zu schaffen.
-
Physik und Unterstützung:
- Voxel-Unterstützung: Voxels werden nur platziert, wenn sie von anderen Voxeln unterstützt werden, um realistische Strukturen zu gewährleisten.
- Kollisionsprüfung: Ameisen ändern ihre Richtung, wenn sie auf Hindernisse stoßen, was natürliche Hindernisvermeidung simuliert.
-
Kamera und Interaktivität:
- Kamera-Steuerung: Die Kamera kann auf einen ausgewählten Voxel fokussiert werden, um detaillierte Beobachtungen zu ermöglichen.
- Benutzeroberfläche: Einfache UI-Elemente ermöglichen das Ein- und Ausschalten der Pheromonenanzeige und der Untergrundansicht.
-
Tag/Nacht-Zyklus:
- Sonnenrichtung und Beleuchtung: Der Tag/Nacht-Zyklus beeinflusst die Beleuchtung in der Szene, was stimmungsvolle Veränderungen erzeugt.
-
Verbesserte Struktur und Klarheit:
- Klassen und Funktionen: Die Klassen und Funktionen sind klar strukturiert, um die Wartbarkeit und Erweiterbarkeit des Codes zu gewährleisten.
- Kommentare und Docstrings: Zusätzliche Kommentare und Docstrings helfen dabei, den Code verständlicher zu machen und zukünftige Erweiterungen zu erleichtern.
Hinweise zur weiteren Entwicklung
-
Verbesserung der Modelle:
- Ersetzen Sie die Platzhalter-Box-Modelle durch detailliertere Modelle für Voxels und Ameisen, um die visuelle Qualität zu erhöhen.
-
Erweiterung der Ameisen-Logik:
- Fügen Sie weitere Verhaltensweisen hinzu, wie z.B. das Sammeln von Materialien zum Bauen des Nestes oder komplexere Interaktionen zwischen Ameisen.
-
Optimierung der Performance:
- Bei großen Umgebungen und vielen Ameisen kann die Performance beeinträchtigt werden. Optimieren Sie den Code durch effizientere Datenstrukturen und Parallelisierung der Aufgaben.
-
Erweiterte Physik:
- Implementieren Sie realistischere Physik, wie z.B. die Interaktion zwischen Voxels und die Auswirkungen von Bewegungen der Ameisen auf die Umgebung.
-
Erweiterte Benutzerinteraktion:
- Fügen Sie weitere UI-Elemente hinzu, um verschiedene Aspekte der Simulation zu steuern, wie z.B. das Hinzufügen von Hindernissen oder das Anpassen von Parametern während der Laufzeit.
-
Detaillierte Pheromon-Visualisierung:
- Entwickeln Sie eine differenziertere Pheromon-Visualisierung, die nicht nur die Stärke, sondern auch die Richtung der Pheromonspuren anzeigt.
Mit diesen Verbesserungen und dem kombinierten Skript sollte die Anwendung den Anforderungen an Realismus und Authentizität gerecht werden und gleichzeitig eine flexible und wartbare Basis für weitere Entwicklungen bieten.
-