skip to content
->

BGGCard: Mi Componente Astro para Mostrar Juegos de Mesa

/ 5 min read

Table of Contents
BGGCard

¿Por qué hice este componente?

Los que me conocen saben que me encantan los juegos de mesa. Tengo una colección grande (y creciendo 😅), y cada cierto tiempo me gusta escribir reseñas o recomendaciones en el blog. Pero siempre me pasaba lo mismo: tenía que copiar manualmente la información básica del juego —año, jugadores, duración, editorial, rating— desde BoardGameGeek. Y hacer eso una y otra vez es aburrido, propenso a errores, y sinceramente me quitaba las ganas de escribir.

Así que decidí crear BGGCard, un componente de Astro que se encarga de hacer todo ese trabajo repetitivo por mí. Solo le paso el ID del juego, y automáticamente trae la información oficial desde la API de BoardGameGeek y la muestra en una tarjeta bonita y consistente. Esto me permite concentrarme en lo que realmente quiero escribir: mi experiencia con el juego y mis opiniones personales.

¿Qué es BGGCard?

BGGCard es un componente de Astro que te permite mostrar tarjetas interactivas con información detallada de juegos de mesa obtenida directamente de la API de BoardGameGeek. Ideal para blogs, reseñas o artículos sobre juegos.

El componente se conecta a la API de BoardGameGeek, obtiene los datos del juego y los muestra en una tarjeta visualmente atractiva con toda la información relevante.

Características Principales

✨ Información Completa del Juego

  • Portada e imagen del juego
  • Título y año de publicación
  • Número de jugadores (mínimo y máximo)
  • Duración de partida (en minutos)
  • Edad recomendada
  • Fabricante/Editorial
  • Rating y evaluaciones de usuarios
  • Nivel de complejidad
  • Descripción completa del juego

🔄 Manejo Inteligente de API

  • Reintentos automáticos cuando la API está procesando (HTTP 202)
  • Polling exponencial para optimizar tiempos de respuesta
  • Autenticación requerida con token de Bearer

🎨 Diseño Responsive

  • Se adapta automáticamente a todos los tamaños de pantalla
  • Tema claro/oscuro integrado con el blog
  • Clases CSS personalizables

Requisitos Previos

1. Token de BoardGameGeek (REQUERIDO)

El token es obligatorio para que el componente funcione. Sin él, la API de BoardGameGeek rechazará las solicitudes.

Pasos para obtener tu token:

  1. Ve a https://boardgamegeek.com/application
  2. Inicia sesión con tu cuenta de BoardGameGeek (crea una si no tienes)
  3. Copia el token proporcionado
  4. Configúralo como variable de entorno BGG_TOKEN

En .env o .env.local:

Terminal window
BGG_TOKEN=tu_token_aqui

Nota: El token es personal y no debe compartirse públicamente. Mantenlo en variables de entorno, nunca en el código fuente.

2. ID del Juego

Necesitas el ID del juego de BoardGameGeek. Puedes encontrarlo en la URL del juego:

  • URL: https://boardgamegeek.com/boardgame/174430/gloomhaven
  • ID: 174430

Cómo Usar el Componente

Importar el Componente

En tu archivo .mdx:

import BGGCard from "@/components/BGGCard.astro";

Sintaxis Básica

<BGGCard gameId="174430" />

Con Clases CSS Personalizadas

<BGGCard
gameId="174430"
class="rounded-lg shadow-xl"
/>

Ejemplos de Uso

Ejemplo 1: Gloomhaven

A continuación se muestra un ejemplo real del componente mostrando Gloomhaven, uno de los juegos de mesa más populares:

Gloomhaven cover

Gloomhaven (2017)

Nro. de Jugadores: 1-4 Jugadores

Tiempo de Juego: 60-120 min

Edad Recomendada: 14+

Fabricante: Cephalofair Games

Descripción:

Gloomhaven is a game of Euro-inspired tactical combat in a persistent world of shifting motives. Players will take on the roles of wandering adventurers with their own special sets of skills and their own reasons for traveling to this dark corner of the world. Players must work together out of necessity to clear out menacing dungeons and forgotten ruins. In the process, they will enhance their abilities with experience and loot, discover new locations to explore and plunder, and expand an ever-branching story fueled by the decisions they make. This is a game with a persistent and changing world that is ideally played over many game sessions. After a scenario, players will make decisions about what to do next, which will determine how the story continues, kind of like a &ldquo;Choose Your Own Adventure&rdquo; book. Playing through a scenario is a co-operative affair where players will fight against automated monsters using an innovative card system to determine the order of play and what a player does on their turn. Each turn, a player chooses two cards to play out of their hand. The number on the top card determines their initiative for the round. Each card also has a top and bottom power, and when it is a player&rsquo;s turn in the initiative order, they determine whether to use the top power of one card and the bottom power of the other, or vice-versa. Players must be careful, though, because over time they will permanently lose cards from their hands. If they take too long to clear a dungeon, they may end u exhausted and be forced to retreat.

Ejemplo 2: Catan (Los Colonos de Catán)

Otro clásico que siempre recomiendo:

Catan cover

Catan (1995)

Nro. de Jugadores: 3-4 Jugadores

Tiempo de Juego: 60-120 min

Edad Recomendada: 10+

Fabricante: KOSMOS

Descripción:

In CATAN (formerly The Settlers of Catan), players try to be the dominant force on the island of Catan by building settlements, cities and roads. On each turn dice are rolled to determine which resources the island produces. Players build structures by 'spending' resources (sheep, wheat, wood, brick and ore) which are represented by the relevant resource cards; each land type, with the exception of the unproductive desert, produces a specific resource: hills produce brick, forests produce wood, mountains produce ore, fields produce wheat, and pastures produce sheep. Set-up includes randomly placing large hexagonal tiles (each depicting one of the five resource-producing terrain types--or the desert) in a honeycomb shape and surrounding them with water tiles, some of which contain ports of exchange. A number disk, the value of which will correspond to the roll of two 6-sided dice, are placed on each terrain tile. Each player is given two settlements (think: houses) and roads (sticks) which are placed on intersections and borders of the terrain tiles. Players collect a hand of resource cards based on which terrain tiles their last-placed settlement is adjacent to. A robber pawn is placed on the desert tile. A turn consists of rolling the dice, collecting resource cards based on this dice roll and the position of settlements (or upgraded cities&mdash;think: hotels), turning in resource cards (if possible and desired) for improvements, trading cards at a port, possibly playing a development card, or trading resource cards with other players. If the dice roll is a 7, the active player moves the robber to a new terrain tile and steals a resource card from another player who has a settlement adjacent to that tile. Points are accumulated by building settlements and cities, having the longest road or the largest army (from some of the development cards), and gathering certain development cards that simply award victory points. When a player has gathered 10 points (some of which may be held in secret), s/he announces this and claims the win.

Ejemplo 3: Ticket to Ride

Un juego más accesible y familiar:

Ticket to Ride cover

Ticket to Ride (2004)

Nro. de Jugadores: 2-5 Jugadores

Tiempo de Juego: 30-60 min

Edad Recomendada: 8+

Fabricante: Days of Wonder

Descripción:

With elegantly simple gameplay, Ticket to Ride can be learned in under 15 minutes. Players collect cards of various types of train cars they then use to claim railway routes in North America. The longer the routes, the more points they earn. Additional points come to those who fulfill Destination Tickets &ndash; goal cards that connect distant cities; and to the player who builds the longest continuous route. "The rules are simple enough to write on a train ticket &ndash; each turn you either draw more cards, claim a route, or get additional Destination Tickets," says Ticket to Ride author, Alan R. Moon. "The tension comes from being forced to balance greed &ndash; adding more cards to your hand, and fear &ndash; losing a critical route to a competitor." Ticket to Ride continues in the tradition of Days of Wonder's big format board games featuring high-quality illustrations and components including: an oversize board map of North America, 225 custom-molded train cars, 144 illustrated cards, and wooden scoring markers. Since its introduction and numerous subsequent awards, Ticket to Ride has become the BoardGameGeek epitome of a "gateway game" -- simple enough to be taught in a few minutes, and with enough action and tension to keep new players involved and in the game for the duration. Part of the Ticket to Ride series.

Información Mostrada por el Componente

El componente muestra los siguientes datos del juego:

CampoDescripción
ImagenPortada o thumbnail del juego
Título y AñoNombre del juego y año de publicación
JugadoresRango de jugadores (ej: 1-4 Jugadores)
DuraciónTiempo de juego en minutos
Edad RecomendadaEdad mínima sugerida
FabricanteEditorial/Fabricante
ComplejidadEscala de 0-5 según BGG
RatingCalificación promedio de usuarios
Usuarios que VotaronCantidad de evaluaciones
DescripciónSinopsis completa del juego

Personalización

Aplicar Estilos Personalizados

Puedes pasar clases de Tailwind a través de la prop class:

<BGGCard
gameId="174430"
class="border-2 border-accent rounded-lg"
/>

Manejo de Errores

El componente maneja automáticamente varios escenarios:

  • ❌ Sin gameId: Muestra mensaje de error
  • ❌ Sin token configurado: Muestra error (token requerido)
  • ❌ Error de API: Muestra mensaje de error descriptivo
  • ⏳ Cargando: Muestra estado “Cargando información del juego…”

Casos de Uso

📝 Reseñas de Juegos: Incluye tarjetas en tus posts de reseñas para mostrar información oficial

🎯 Recomendaciones: Destaca juegos recomendados con información completa

📚 Colecciones: Documenta tu colección de juegos en el blog

🎓 Educativo: Enseña sobre diferentes juegos y sus características

Cómo Encontrar el Código

El código fuente del componente está disponible en GitHub:

Repositorio: https://github.com/chardila/blogcardila

Ruta del componente:

blog/src/components/BGGCard.astro

URL directa en GitHub:

https://github.com/chardila/blogcardila/blob/master/blog/src/components/BGGCard.astro

Características Técnicas

Parsing XML sin Dependencias

El componente usa expresiones regulares para parsear XML sin necesidad de librerías externas:

const getAttr = (tag: string, attr: string): string | null => {
const regex = new RegExp(`<${tag}[^>]*?${attr}=["']([^"']+)["']`, 'i');
const match = xmlText?.match(regex);
return match ? match[1] : null;
};

Polling Automático

Cuando BoardGameGeek devuelve un HTTP 202 (queued), el componente reintentar automáticamente:

while (res.status === 202 && tries < 8) {
await new Promise((r) => setTimeout(r, 1000 + tries * 500));
res = await fetch(endpoint, { headers });
tries += 1;
}

Decodificación de Entidades HTML

Las descripciones se limpian y decodifican automáticamente:

description = description
.replace(/&amp;/g, '&')
.replace(/&lt;/g, '<')
.replace(/&quot;/g, '"')
.replace(/<[^>]+>/g, '') // Remove HTML tags
.trim();

Ejemplo Completo en un Post

---
import BGGCard from "@/components/BGGCard.astro";
---
# Mi Juego Favorito: Gloomhaven
Gloomhaven es un juego de dungeon crawling increíble que...
<BGGCard gameId="174430" />
El componente anterior muestra la información oficial del juego.

Solución de Problemas

”BGG_TOKEN env var not found”

Solución: Este error indica que tu token no está configurado. Es obligatorio para que el componente funcione.

  1. Obtén tu token en https://boardgamegeek.com/application
  2. Configúralo en .env.local o .env como BGG_TOKEN=tu_token
  3. Reinicia el servidor de desarrollo

”BGG API error: 401”

Solución: Tu token es inválido o ha expirado.

  1. Verifica que has copiado el token completo y sin espacios
  2. Obtén un nuevo token en https://boardgamegeek.com/application
  3. Actualiza tu variable de entorno

API retorna timeout

La API de BoardGameGeek puede ser lenta ocasionalmente. El componente reintentar automáticamente hasta 8 veces antes de fallar. Si persiste, intenta más tarde.

Imagen no aparece

Algunos juegos no tienen imagen en BGG. El componente usa thumbnail como fallback automáticamente.

Conclusión

BGGCard es una forma elegante y eficiente de integrar información oficial de BoardGameGeek en tus posts sin tener que escribir manualmente todos los detalles de cada juego. Perfecto para bloggers que escriben sobre juegos de mesa.

¿Preguntas o sugerencias? ¡No dudes en revisar el código en GitHub!

Comentarios

Cargando comentarios...

Deja un comentario. Solo necesitas verificar tu email una vez.