// recursos

Chuletas & Referencias

Todo lo que necesitas para los retos, sin salir de la plataforma.

🕹️ Mecánica del canvas

Coordenadasinfo
Canvas: 480 × 320 px
(0, 0)   → esquina superior izquierda
(480, 0) → esquina superior derecha
(240, 160) → centro
y=290  → suelo (donde corre el sprite)
Estados del spriteinfo
"run"   → corre hacia la derecha
"jump"  → saltando / en el aire
"idle"  → quieto, esperando
"win"   → victoria (animación final)
"die"   → muerte (test fallido)
Estructura de un framepython
{"x": 120, "y": 290, "state": "run"}

# x: posición horizontal (0-480)
# y: posición vertical (0-320)
# state: animación activa
Template básico Pythonpython
import json

frames = []
x, y = 60, 290

for _ in range(18):
    frames.append({"x": x, "y": y, "state": "run"})
    x += 20

frames.append({"x": x, "y": y, "state": "win"})
print(json.dumps(frames))

🔍 Búsqueda

BFS — Más corto garantizadopython
from collections import deque

def bfs(start, goal, grid):
    queue = deque([(start, [start])])
    visited = {start}
    while queue:
        (x, y), path = queue.popleft()
        if (x, y) == goal:
            return path
        for nx, ny in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]:
            if (nx, ny) not in visited and es_valid(nx, ny):
                visited.add((nx, ny))
                queue.append(((nx, ny), path + [(nx, ny)]))
Ir hacia un objetivopython
def mover_hacia(x, y, tx, ty, speed=12):
    dx, dy = tx - x, ty - y
    dist = (dx**2 + dy**2) ** 0.5
    if dist < speed:
        return tx, ty
    return x + dx/dist * speed, y + dy/dist * speed

# Uso:
for _ in range(50):
    x, y = mover_hacia(x, y, target_x, target_y)
    frames.append({"x": round(x), "y": round(y), "state": "run"})
    if abs(x - target_x) < 12: break
Visitar múltiples waypointspython
waypoints = [(100, 200), (300, 150), (420, 290)]

for tx, ty in waypoints:
    for _ in range(60):
        x, y = mover_hacia(x, y, tx, ty)
        frames.append({"x": round(x), "y": round(y), "state": "run"})
        if abs(x - tx) < 12 and abs(y - ty) < 12:
            break

⚙️ Estructuras de datos

Pila (LIFO)python
stack = []
stack.append(item)   # push
item = stack.pop()   # pop — último añadido

# Útil para: deshacer pasos, DFS, recursión
Cola (FIFO)python
from collections import deque
queue = deque()
queue.append(item)       # enqueue
item = queue.popleft()   # dequeue — primero añadido

# Útil para: BFS, procesar en orden
Heap mínimopython
import heapq
heap = []
heapq.heappush(heap, (priority, x, y))
priority, x, y = heapq.heappop(heap)  # el menor

# Útil para: Dijkstra, greedy por distancia

⚡ Optimización

Memoización (caché)python
memo = {}

def f(n):
    if n in memo:
        return memo[n]
    resultado = calcular(n)
    memo[n] = resultado
    return resultado

# O con decorador:
from functools import lru_cache

@lru_cache(maxsize=None)
def f(n): ...
Greedy — siempre el más cercanopython
puntos = [(100,200), (300,150), (80,290)]
x, y = 60, 290  # posición inicial

while puntos:
    # Selecciona el punto más cercano
    closest = min(puntos,
                  key=lambda p: (p[0]-x)**2 + (p[1]-y)**2)
    puntos.remove(closest)
    mover_a(closest)

🤖 IA Básica

Seguir al héroepython
def seguir(npc_x, npc_y, hero_x, hero_y, speed=10):
    dx = hero_x - npc_x
    dy = hero_y - npc_y
    dist = (dx**2 + dy**2) ** 0.5
    if dist > speed:
        npc_x += dx / dist * speed
        npc_y += dy / dist * speed
    return npc_x, npc_y
Comportamiento flee/followpython
SAFE_DIST = 120

dist_enemy = ((x - ex)**2 + (y - ey)**2) ** 0.5

if dist_enemy < SAFE_DIST:
    # Huir: alejarse del enemigo
    dx, dy = x - ex, y - ey
    dist = (dx**2 + dy**2) ** 0.5
    x += dx / dist * speed
    y += dy / dist * speed
else:
    # Avanzar hacia el objetivo
    x += speed