import sys import math import random import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * # ========================================== # CONFIGURACIÓN Y CONSTANTES # ========================================== WIDTH, HEIGHT = 800, 600 # Colores (R, G, B) COLOR_BG = (0.12, 0.15, 0.12) # Fondo ambiente COLOR_WATER = (0.0, 0.5, 0.85) # Agua animada (Cian/Azul) COLOR_LAND = (0.45, 0.32, 0.15) # Tierra / Relieve COLOR_LAND_RIVER = (0.40, 0.28, 0.12) # Tierra en riachuelos COLOR_ISLAND = (0.5, 0.38, 0.18) # Islas COLOR_REED = (0.15, 0.85, 0.25) # Juncos verdes COLOR_DRAGONFLY = (0.0, 1.0, 1.0) # Libélula alámbrica (Cian) COLOR_MOSQUITO = (1.0, 0.2, 0.2) # Mosquitos (Rojo) COLOR_FLY = (1.0, 0.9, 0.0) # Moscas (Amarillo/Dorado) # Dimensiones del Mundo POND_RADIUS = 1800.0 # Estanque de 1800u de superficie STREAM_LEN = 900.0 # Longitud de cada arroyo STREAM_MIN_Y = -(POND_RADIUS + STREAM_LEN) # -2700.0 STREAM_MAX_Y = (POND_RADIUS + STREAM_LEN) # 2700.0 WORLD_LEN = STREAM_MAX_Y - STREAM_MIN_Y # Cantidades de insectos MOSQUITO_MIN, MOSQUITO_MAX = 10, 20 FLY_MIN, FLY_MAX = 2, 7 # ========================================== # ELEMENTOS DEL MAPA # ========================================== REEDS = [ # Juncos en islas del estanque principal (-250, 350, 0, 20), (-160, -500, 0, 22), (500, 200, 0, 24), (-700, 200, 0, 21), (200, -800, 0, 23), (-900, -300, 0, 25), (760, -600, 0, 22), (900, 500, 0, 26), (-500, 900, 0, 23), (600, -1000, 0, 22), (-1200, 400, 0, 24), (1300, -300, 0, 20), (-1400, -700, 0, 25), (1100, 1200, 0, 23), (-360, -1300, 0, 22), # Juncos en el arroyo inferior (-90, -1950, 0, 20), (-110, -2150, 0, 23), (-80, -2350, 0, 19), (-100, -2550, 0, 22), # Juncos en el arroyo superior (90, 1950, 0, 22), (110, 2150, 0, 20), (85, 2350, 0, 24), (105, 2550, 0, 21) ] ISLANDS = [ (-250, 350, 90), (-160, -500, 85), (500, 200, 100), (-700, 200, 110), (200, -800, 95), (-900, -300, 120), (760, -600, 90), (900, 500, 105), (-500, 900, 115), (600, -1000, 100) ] def get_river_center(y): """Devuelve el centro X del arroyo fuera de los límites del estanque central.""" if y < -POND_RADIUS: dy = y + POND_RADIUS return -50 + 100 * math.sin(dy * 0.008) elif y > POND_RADIUS: dy = y - POND_RADIUS return 50 + 100 * math.sin(dy * 0.008) else: return (y / POND_RADIUS) * 50.0 def is_over_water(x, y): """Comprueba si unas coordenadas (x, y) están dentro del agua.""" dist_center = math.hypot(x, y) if dist_center < POND_RADIUS - 50: return True if abs(y) >= POND_RADIUS: cx = get_river_center(y) if abs(x - cx) < 80: return True return False def get_random_water_position(): """Genera una posición inicial aleatoria sobre el agua.""" while True: if random.random() < 0.7: rad = random.uniform(0, math.pi * 2) r = random.uniform(100, POND_RADIUS - 150) x = r * math.cos(rad) y = r * math.sin(rad) else: y = random.choice([random.uniform(POND_RADIUS, STREAM_MAX_Y), random.uniform(STREAM_MIN_Y, -POND_RADIUS)]) cx = get_river_center(y) x = cx + random.uniform(-60, 60) if is_over_water(x, y): z = random.uniform(5.0, 35.0) return x, y, z # ========================================== # CLASES DE INSECTOS # ========================================== class Insect: def __init__(self, insect_type): self.type = insect_type self.x, self.y, self.z = get_random_water_position() self.yaw = random.uniform(0, 360) self.timer = random.uniform(0, 100) if self.type == "mosquito": self.speed = 1.8 self.size = 1.2 else: # Fly self.speed = 0.9 self.size = 1.6 def update(self, player_pos): self.timer += 0.05 px, py, pz = player_pos dist_to_player = math.hypot(self.x - px, self.y - py) if self.type == "mosquito": if dist_to_player < 100: escape_angle = math.degrees(math.atan2(self.y - py, self.x - px)) self.yaw += (escape_angle - self.yaw) * 0.05 self.yaw += math.sin(self.timer * 3) * 1.5 self.z += math.sin(self.timer * 1.5) * 0.2 elif self.type == "fly": if dist_to_player < 120: escape_angle = math.degrees(math.atan2(self.y - py, self.x - px)) self.yaw = escape_angle + random.uniform(-45, 45) self.z += random.choice([-1.5, 1.5]) else: if random.random() < 0.08: self.yaw += random.uniform(-60, 60) self.yaw += math.sin(self.timer * 6) * 4.0 self.z += math.cos(self.timer * 4) * 0.6 self.z = max(3.0, min(50.0, self.z)) rad = math.radians(self.yaw) next_x = self.x - math.sin(rad) * self.speed next_y = self.y + math.cos(rad) * self.speed if is_over_water(next_x, next_y): self.x, self.y = next_x, next_y else: self.yaw += 140.0 + random.uniform(-20, 20) if self.y > STREAM_MAX_Y: self.y -= WORLD_LEN elif self.y < STREAM_MIN_Y: self.y += WORLD_LEN def draw(self, attached=False): if self.type == "mosquito": glColor3f(*COLOR_MOSQUITO) else: glColor3f(*COLOR_FLY) glPushMatrix() if not attached: glTranslatef(self.x, self.y, self.z) glRotatef(self.yaw, 0, 0, 1) s = self.size glBegin(GL_LINES) # Cuerpo glVertex3f(0, s, 0) glVertex3f(0, -s, 0) # Alas w_offset = 0.0 if attached else math.sin(self.timer * 30) * (s * 0.8) glVertex3f(0, 0, 0) glVertex3f(-s * 1.5, 0, w_offset) glVertex3f(0, 0, 0) glVertex3f(s * 1.5, 0, w_offset) glEnd() glPopMatrix() # ========================================== # RENDERIZADO DEL ESCENARIO # ========================================== def draw_water_surface(time_counter): """Dibuja una malla 3D animada para el agua.""" glColor3f(*COLOR_WATER) grid_size = 30 for x in range(int(-POND_RADIUS), int(POND_RADIUS), grid_size): glBegin(GL_LINE_STRIP) for y in range(int(-POND_RADIUS), int(POND_RADIUS), grid_size): dist = math.hypot(x, y) if dist < POND_RADIUS - 30: z = 1.0 * math.sin(dist * 0.015 - time_counter * 3.0) + 0.5 * math.cos(x * 0.01 + time_counter) glVertex3f(x, y, z) glEnd() for y in range(int(STREAM_MIN_Y), int(STREAM_MAX_Y), 20): if abs(y) < POND_RADIUS: continue cx = get_river_center(y) glBegin(GL_LINE_STRIP) for dx in range(-100, 110, 15): x = cx + dx z = 0.5 * math.sin(y * 0.03 + dx * 0.08 + time_counter * 4.0) glVertex3f(x, y, z) glEnd() def draw_terrain(): """Dibuja el terreno del mapa.""" glColor3f(*COLOR_LAND) grid_step = 120 for y in range(int(STREAM_MIN_Y - 300), int(STREAM_MAX_Y + 300), grid_step): glBegin(GL_LINE_STRIP) for x in range(-2500, 2500, grid_step): z = 1.5 * math.sin(x * 0.005) + 1.5 * math.cos(y * 0.005) glVertex3f(x, y, z) glEnd() width_river = 100.0 margin_land = 70.0 glColor3f(*COLOR_LAND_RIVER) for y in range(int(STREAM_MIN_Y), int(STREAM_MAX_Y), 30): if abs(y) < POND_RADIUS: continue cx = get_river_center(y) # Orilla Izquierda glBegin(GL_LINE_STRIP) for dx in range(int(-width_river - margin_land), int(-width_river), 15): x = cx + dx z = 0.6 * math.sin(y * 0.02 + x * 0.02) + 0.3 glVertex3f(x, y, z) glEnd() # Orilla Derecha glBegin(GL_LINE_STRIP) for dx in range(int(width_river), int(width_river + margin_land), 15): x = cx + dx z = 0.6 * math.sin(y * 0.02 + x * 0.02) + 0.3 glVertex3f(x, y, z) glEnd() for ix, iy, ir in ISLANDS: glColor3f(*COLOR_ISLAND) for layer in range(1, 4): rad_layer = ir * (1 - layer * 0.25) height = layer * 1.2 glBegin(GL_LINE_LOOP) for i in range(16): angle = 2.0 * math.pi * i / 16 dx = rad_layer * math.cos(angle) dy = rad_layer * math.sin(angle) glVertex3f(ix + dx, iy + dy, height) glEnd() def draw_map(time_counter): """Dibuja todo el mapa.""" draw_terrain() draw_water_surface(time_counter) glColor3f(*COLOR_REED) glBegin(GL_LINES) for rx, ry, rz, rh in REEDS: glVertex3f(rx, ry, rz) glVertex3f(rx, ry, rz + rh) glVertex3f(rx, ry, rz) glVertex3f(rx - 1.5, ry + 0.5, rz + rh * 0.7) glVertex3f(rx, ry, rz) glVertex3f(rx + 1.5, ry - 0.5, rz + rh * 0.8) glEnd() # ========================================== # MODELO 3D DE LA LIBÉLULA # ========================================== def draw_dragonfly(wing_angle, caught_insect=None): """Dibuja la libélula y el insecto atrapado en sus patas si tiene uno.""" glColor3f(*COLOR_DRAGONFLY) # Cuerpo glBegin(GL_LINES) glVertex3f(0, 1.5, 0) glVertex3f(0, -3.0, 0) glVertex3f(-0.4, 0.6, 0) glVertex3f(0.4, 0.6, 0) glVertex3f(-0.3, -0.6, 0) glVertex3f(0.3, -0.6, 0) # Patas (Visibles sujetando al insecto) glVertex3f(-0.3, 0.5, 0) glVertex3f(-0.2, 0.2, -0.6) glVertex3f(0.3, 0.5, 0) glVertex3f(0.2, 0.2, -0.6) glVertex3f(-0.2, -0.2, 0) glVertex3f(-0.1, -0.3, -0.6) glVertex3f(0.2, -0.2, 0) glVertex3f(0.1, -0.3, -0.6) glEnd() # Cabeza glBegin(GL_LINE_LOOP) for i in range(8): angle = 2.0 * math.pi * i / 8 glVertex3f(0.3 * math.cos(angle), 1.4 + 0.3 * math.sin(angle), 0) glEnd() # Alas rad_wing = math.radians(wing_angle) w_z = math.sin(rad_wing) * 1.2 if wing_angle != 0 else 0.0 glBegin(GL_LINE_LOOP) glVertex3f(0, 0.6, 0) glVertex3f(-4.5, 1.0, w_z) glVertex3f(-3.8, 0.2, w_z) glEnd() glBegin(GL_LINE_LOOP) glVertex3f(0, 0.6, 0) glVertex3f(4.5, 1.0, w_z) glVertex3f(3.8, 0.2, w_z) glEnd() glBegin(GL_LINE_LOOP) glVertex3f(0, -0.1, 0) glVertex3f(-3.8, -0.2, w_z) glVertex3f(-3.0, -0.8, w_z) glEnd() glBegin(GL_LINE_LOOP) glVertex3f(0, -0.1, 0) glVertex3f(3.8, -0.2, w_z) glVertex3f(3.0, -0.8, w_z) glEnd() # Si lleva un insecto atrapado, se dibuja sujeto bajo su tórax if caught_insect: glPushMatrix() glTranslatef(0.0, 0.2, -0.6) # Posición bajo las patas caught_insect.draw(attached=True) glPopMatrix() # ========================================== # BUCLE PRINCIPAL Y LÓGICA # ========================================== def main(): pygame.init() pygame.display.set_mode((WIDTH, HEIGHT), DOUBLEBUF | OPENGL) glEnable(GL_DEPTH_TEST) glClearColor(*COLOR_BG, 1.0) glMatrixMode(GL_PROJECTION) gluPerspective(50, (WIDTH / HEIGHT), 0.1, 5000.0) glMatrixMode(GL_MODELVIEW) # Estado de la Libélula px, py, pz = 0.0, 0.0, 15.0 yaw = 0.0 roll = 0.0 pitch = 0.0 max_roll = 30.0 max_pitch = 20.0 speed = 0.0 max_speed = 3.0 acceleration = 0.06 deceleration = 0.03 min_altitude = 1.0 max_altitude = 120.0 wing_timer = 0.0 water_timer = 0.0 is_perched = False # Estado de Caza caught_insect = None # Insecto sujeto actualmente en las patas eaten_mosquitos = 0 # Contador de mosquitos comidos eaten_flies = 0 # Contador de moscas comidas def update_title(): status = " (Llevando presa a un junco...)" if caught_insect else "" pygame.display.set_caption( f"Libélula 3D | Mosquitos cazados: {eaten_mosquitos} | Moscas cazadas: {eaten_flies}{status}" ) update_title() # Inicializar Insectos insects = [] num_mosquitos = random.randint(MOSQUITO_MIN, MOSQUITO_MAX) num_flies = random.randint(FLY_MIN, FLY_MAX) for _ in range(num_mosquitos): insects.append(Insect("mosquito")) for _ in range(num_flies): insects.append(Insect("fly")) clock = pygame.time.Clock() running = True while running: dt = clock.tick(60) / 1000.0 water_timer += dt for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): running = False keys = pygame.key.get_pressed() # CONTROLES Y MOVIMIENTO DE LA LIBÉLULA if is_perched: if keys[K_LEFT]: yaw += 3.0 if keys[K_RIGHT]: yaw -= 3.0 if keys[K_UP]: is_perched = False speed = 0.5 wing_angle = 0.0 pitch = 0.0 roll = 0.0 else: if keys[K_UP]: speed = min(speed + acceleration, max_speed) elif keys[K_DOWN]: speed = max(speed - deceleration, 0.0) # Intentar posarse en la punta de un junco if speed < 0.3: for rx, ry, rz, rh in REEDS: dist = math.hypot(px - rx, py - ry) if dist < 8.0 and abs(pz - (rz + rh)) < 8.0: px, py, pz = rx, ry, rz + rh speed = 0.0 roll = 0.0 pitch = 0.0 is_perched = True # Si lleva una presa al posarse, se la come if caught_insect: if caught_insect.type == "mosquito": eaten_mosquitos += 1 else: eaten_flies += 1 caught_insect = None update_title() break target_pitch = 0.0 if keys[K_w]: pz = min(pz + 0.8, max_altitude) target_pitch = max_pitch elif keys[K_s]: pz = max(pz - 0.8, min_altitude) target_pitch = -max_pitch pitch += (target_pitch - pitch) * 0.15 target_roll = 0.0 if keys[K_LEFT]: yaw += 2.8 target_roll = -max_roll elif keys[K_RIGHT]: yaw -= 2.8 target_roll = max_roll roll += (target_roll - roll) * 0.15 rad_yaw = math.radians(yaw) px += -math.sin(rad_yaw) * speed py += math.cos(rad_yaw) * speed if abs(py) < POND_RADIUS: max_limit_x = POND_RADIUS + 200.0 else: cx = get_river_center(py) max_limit_x = abs(cx) + 200.0 px = max(-max_limit_x, min(max_limit_x, px)) if py > STREAM_MAX_Y: py -= WORLD_LEN elif py < STREAM_MIN_Y: py += WORLD_LEN wing_timer += 60.0 if speed > 0.1 else 30.0 wing_angle = math.sin(wing_timer) * 35.0 # ACTUALIZACIÓN DE INSECTOS current_mosquitos = 0 current_flies = 0 for insect in insects[:]: insect.update((px, py, pz)) if insect.type == "mosquito": current_mosquitos += 1 else: current_flies += 1 # Detección de contacto/choque con la libélula if not caught_insect: dist_to_dragonfly = math.sqrt((px - insect.x)**2 + (py - insect.y)**2 + (pz - insect.z)**2) if dist_to_dragonfly < 6.0: # Rozamiento o choque caught_insect = insect insects.remove(insect) update_title() # Mantener poblaciones dentro del rango if current_mosquitos < MOSQUITO_MIN: insects.append(Insect("mosquito")) if current_flies < FLY_MIN: insects.append(Insect("fly")) # RENDERIZADO glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() cam_dist = 18.0 cam_height = 8.0 rad_yaw = math.radians(yaw) cam_x = px + math.sin(rad_yaw) * cam_dist cam_y = py - math.cos(rad_yaw) * cam_dist cam_z = pz + cam_height gluLookAt(cam_x, cam_y, cam_z, px, py, pz + 0.5, 0, 0, 1) draw_map(water_timer) # Dibujar Insectos en el mapa for insect in insects: insect.draw() # Dibujar Libélula (con el insecto en las patas si lo ha capturado) glPushMatrix() glTranslatef(px, py, pz) glRotatef(yaw, 0, 0, 1) glRotatef(pitch, 1, 0, 0) glRotatef(roll, 0, 1, 0) draw_dragonfly(wing_angle, caught_insect) glPopMatrix() pygame.display.flip() pygame.quit() sys.exit() if __name__ == "__main__": main()