Libelula/previos/dragonfly_game_v4.1.py

703 lines
22 KiB
Python

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)
COLOR_HUD = (1.0, 1.0, 1.0) # Retícula HUD (Blanco)
# 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)
glVertex3f(0, s, 0)
glVertex3f(0, -s, 0)
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 DE ESCENARIO Y MODELOS
# ==========================================
def draw_water_surface(time_counter):
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():
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)
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()
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):
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()
def draw_dragonfly(wing_angle, caught_insect=None):
glColor3f(*COLOR_DRAGONFLY)
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)
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()
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()
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()
if caught_insect:
glPushMatrix()
glTranslatef(0.0, 0.2, -0.6)
caught_insect.draw(attached=True)
glPopMatrix()
# ==========================================
# INTERFAZ 2D / RADAR / HUD
# ==========================================
def draw_hud(player_pos, yaw, insects, eaten_mosquitos, eaten_flies, font):
"""Dibuja el Radar central y los contadores en 2D superpuestos."""
glDisable(GL_DEPTH_TEST)
# Cambiar a proyección 2D ortogonal
glMatrixMode(GL_PROJECTION)
glPushMatrix()
glLoadIdentity()
gluOrtho2D(0, WIDTH, 0, HEIGHT)
glMatrixMode(GL_MODELVIEW)
glPushMatrix()
glLoadIdentity()
px, py, pz = player_pos
# ----------------------------------
# 1. RADAR / MIRILLA (Centro Superior)
# ----------------------------------
cx, cy = WIDTH // 2, HEIGHT - 70
radius = 45
# Dibujar Círculo exterior
glColor3f(*COLOR_HUD)
glBegin(GL_LINE_LOOP)
for i in range(32):
angle = 2.0 * math.pi * i / 32
glVertex2f(cx + radius * math.cos(angle), cy + radius * math.sin(angle))
glEnd()
# Dibujar Cruz Central y Horizonte en línea discontinua
glBegin(GL_LINES)
glVertex2f(cx, cy + radius)
glVertex2f(cx, cy + radius - 10)
glVertex2f(cx, cy - radius)
glVertex2f(cx, cy - radius + 10)
glVertex2f(cx - radius, cy)
glVertex2f(cx - radius + 10, cy)
glVertex2f(cx + radius, cy)
glVertex2f(cx + radius - 10, cy)
glEnd()
# Cruz pequeña central
glBegin(GL_LINES)
glVertex2f(cx - 4, cy)
glVertex2f(cx + 4, cy)
glVertex2f(cx, cy - 4)
glVertex2f(cx, cy + 4)
glEnd()
# Buscar el insecto más cercano al frente
closest_insect = None
min_dist = 999999.0
relative_angle = 0.0
diff_z = 0.0
rad_yaw = math.radians(yaw)
# Vector dirección del jugador
dir_x = -math.sin(rad_yaw)
dir_y = math.cos(rad_yaw)
for insect in insects:
dx = insect.x - px
dy = insect.y - py
dist = math.hypot(dx, dy)
if dist < min_dist and dist > 0.1:
# Calcular ángulo relativo respecto a hacia dónde mira la libélula
angle_to_insect = math.degrees(math.atan2(dy, dx))
# Ajuste de ángulo respecto al YAW
heading = (angle_to_insect - (90 - yaw)) % 360
if heading > 180:
heading -= 360
# Solo mostrar si está en un cono frontal de visión (120 grados)
if abs(heading) < 60:
min_dist = dist
closest_insect = insect
relative_angle = heading
diff_z = insect.z - pz # Por encima (+) o debajo (-)
# Si hay una presa cercana al frente, dibujarla en la mirilla del radar
if closest_insect:
# Mapear posición horizontal (-60° a +60° -> -radius a +radius)
radar_x = cx - (relative_angle / 60.0) * (radius - 8)
# Mapear altura (-20u a +20u de diferencia -> -radius a +radius)
radar_y = cy + (diff_z / 20.0) * (radius - 8)
# Clampear dentro del círculo del radar
dist_from_center = math.hypot(radar_x - cx, radar_y - cy)
if dist_from_center > (radius - 6):
factor = (radius - 6) / dist_from_center
radar_x = cx + (radar_x - cx) * factor
radar_y = cy + (radar_y - cy) * factor
# Color del punto según la especie
if closest_insect.type == "mosquito":
glColor3f(*COLOR_MOSQUITO)
else:
glColor3f(*COLOR_FLY)
# Dibujar punto e indicador de la presa
glBegin(GL_TRIANGLE_FAN)
for i in range(12):
ang = 2.0 * math.pi * i / 12
glVertex2f(radar_x + 4 * math.cos(ang), radar_y + 4 * math.sin(ang))
glEnd()
# Pequeñas alas en el radar
glBegin(GL_LINES)
glVertex2f(radar_x - 7, radar_y)
glVertex2f(radar_x + 7, radar_y)
glEnd()
# ----------------------------------
# 2. ICONOS Y CONTADORES HUD
# ----------------------------------
# Marcador Izquierdo: Mosquitos
glColor3f(*COLOR_MOSQUITO)
glBegin(GL_LINES)
# Dibujar pequeño ícono de mosquito
glVertex2f(25, HEIGHT - 25)
glVertex2f(25, HEIGHT - 45)
glVertex2f(25, HEIGHT - 35)
glVertex2f(10, HEIGHT - 35)
glVertex2f(25, HEIGHT - 35)
glVertex2f(40, HEIGHT - 35)
glEnd()
# Marcador Derecho: Moscas
glColor3f(*COLOR_FLY)
glBegin(GL_LINES)
# Dibujar pequeño ícono de mosca
glVertex2f(WIDTH - 45, HEIGHT - 25)
glVertex2f(WIDTH - 45, HEIGHT - 45)
glVertex2f(WIDTH - 45, HEIGHT - 35)
glVertex2f(WIDTH - 60, HEIGHT - 35)
glVertex2f(WIDTH - 45, HEIGHT - 35)
glVertex2f(WIDTH - 30, HEIGHT - 35)
glEnd()
# Restaurar matrices 3D
glPopMatrix()
glMatrixMode(GL_PROJECTION)
glPopMatrix()
glMatrixMode(GL_MODELVIEW)
glEnable(GL_DEPTH_TEST)
# Renderizar el texto de los contadores mediante imágenes PyGame
txt_mosq = font.render(f"x {eaten_mosquitos}", True, (255, 60, 60))
txt_flies = font.render(f"x {eaten_flies}", True, (255, 230, 0))
surface = pygame.display.get_surface()
# Crear textura rápida para el texto en pantalla
draw_text_pygame(txt_mosq, 50, 20)
draw_text_pygame(txt_flies, WIDTH - 110, 20)
def draw_text_pygame(text_surface, x, y):
"""Dibuja texto de PyGame en la pantalla de OpenGL."""
text_data = pygame.image.tostring(text_surface, "RGBA", True)
w, h = text_surface.get_size()
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glRasterPos2d(x, HEIGHT - y - h)
glDrawPixels(w, h, GL_RGBA, GL_UNSIGNED_BYTE, text_data)
glDisable(GL_BLEND)
# ==========================================
# BUCLE PRINCIPAL Y LÓGICA
# ==========================================
def main():
pygame.init()
pygame.font.init()
font = pygame.font.SysFont("Arial", 26, bold=True)
pygame.display.set_mode((WIDTH, HEIGHT), DOUBLEBUF | OPENGL)
pygame.display.set_caption("Simulador de Vuelo de Libélula 3D")
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
eaten_mosquitos = 0
eaten_flies = 0
# 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)
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
if caught_insect:
if caught_insect.type == "mosquito":
eaten_mosquitos += 1
else:
eaten_flies += 1
caught_insect = None
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
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:
caught_insect = insect
insects.remove(insect)
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)
for insect in insects:
insect.draw()
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()
# DIBUJAR INTERFAZ (HUD) Y RADAR
draw_hud((px, py, pz), yaw, insects, eaten_mosquitos, eaten_flies, font)
pygame.display.flip()
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()