https://d226lax1qjow5r.cloudfront.net/blog/blogposts/how-to-build-a-role-playing-game-with-vonage-ai-studio-and-notion/rpg_ai-studio-notion.png

Cómo crear un juego de rol con Vonage AI Studio y Notion

Publicado el January 24, 2024

Tiempo de lectura: 7 minutos

De jugar a juegos de rol a construir Vonage's Gate

Cuando era más joven, pasaba parte de mi tiempo jugando a videojuegos que me regalaban, auténticas joyas por derecho propio, pero con los que pasaba demasiado tiempo, a menudo ganándome alguna que otra reprimenda. Disfrutaba con una gran variedad de juegos, desde simulaciones sociales y juegos de plataformas hasta shooters en primera persona y mis favoritos, los juegos de rol (RPG). Sin que yo lo supiera, cada hora que pasaba en esos mundos de fantasía perfeccionaba sutilmente mi creatividad y mi capacidad para resolver problemas. En poco tiempo, esas mismas aventuras de juego sentaron las bases de este blog.

El año pasado, Larian Studios publicó Baldur's Gate 3un RPG basado en el juego de mesa Dungeon & Dragons. Piensa en un RPG como si te sumergieras en un libro en el que, en lugar de leer la historia, te conviertes en el protagonista. Navegarás a través de aventuras, tomarás decisiones, interactuarás con otros personajes y darás forma al desenlace de la historia en función de tus elecciones. Es una oportunidad de experimentar una narrativa de forma práctica, en la que el mundo reacciona a lo que tú decides.

Yo mismo jugué y quedé impresionado por lo única y atractiva que era la experiencia de cada jugador, ya que seguía el estilo de "elige tu propia aventura". Entonces me sentí obligado a recrear una versión más sencilla de un juego de rol utilizando Vonage AI Studio y Messages API - ¡La puerta de Vonage!

Crear un RPG con mensajes

Así es como crearemos una experiencia narrativa en la que los jugadores decidirán el destino de sus personajes. Ahora, canaliza la energía de tu personaje principal, ¡y pongámonos a construir!

Requisitos previos

Base de datos y configuración del juego

¡Como práctica recomendada, almacenaremos todos los valores utilizados en el juego en una base de datos; para este ejemplo, utilizaremos Notion!

Cómo utilizar Notion como base de datos

Es una opción fácil de usar, no requiere conocimientos avanzados de bases de datos y es muy práctica porque los cambios aparecen al instante, lo que es perfecto para mantener nuestro contenido fresco y receptivo. Aunque es menos escalable que las bases de datos tradicionales, puede manejar todo lo que necesitamos para esta aplicación. Lo mejor es que se integra fácilmente con Vonage AI Studio y otras plataformas de código bajo, ¡lo que nos facilita mucho la vida!

Cree su hoja de cálculo

Ir a Noción. Haga clic en el botón (+) para añadir una página. En la nueva página, en BASE DE DATOS, haga clic en "Tabla". Cree las siguientes columnas:

  • ID (tipo: número) - el ID del mensaje se envía por MMS

  • Mensaje (tipo: título) - el texto real enviado

  • Opción1 (tipo: número) - la respuesta que envía un jugador al elegir la opción 1

  • Opción2 (tipo: número) - la respuesta que envía un jugador al elegir la opción 2

  • Opción3 (tipo: número) - la respuesta que envía un jugador al elegir la opción 3

  • NextID1 (tipo: número) - el ID del siguiente mensaje que recibe el jugador después de elegir la opción 1

  • NextID2 (tipo: número) - el ID del siguiente mensaje que recibe el jugador tras elegir la opción 2.

  • NextID3 (tipo: número) - el ID del siguiente mensaje que recibe el jugador después de elegir la opción 3.

Cómo estructurar su juego

Puedes personalizar la historia como quieras. En mi historia, el jugador se queda con el artefacto. Los textos enviados al jugador se activan por sus respuestas al mensaje anterior.

Creación de personajes

  • Mensaje inicial: Envía una breve introducción y una elección sencilla para la creación del personaje.

En mi base de datos, puedes ver que el ID 1 muestra el mensaje inicial: "¡Bienvenido a Vonage's Gate! Elige una clase: (1) Guerrero, (2) Mago, o (3) Pícaro".

  • Confirmación del personaje: Una vez que respondan con una elección, envíe una confirmación con una breve descripción del personaje.

Progresión del juego

Inmediatamente después de la confirmación del personaje, presente el primer escenario sencillo que requiera una decisión. Cuando el jugador haga una elección, responda con un breve resultado y otro punto de decisión. Continúe con una serie de puntos de decisión sencillos que mantengan la historia en movimiento sin requerir interacciones complejas. En esta demostración, los jugadores responderán con mensajes de un solo carácter. Tras unas cuantas rondas de decisiones, podemos concluir la demo con un final sencillo.

The image shows a screenshot of a database table titled "Vonage's Gate Database - Script." The table has several columns: "ID," "Message," "Option1," "Option2," "Option3," "NextID1," "NextID2," and "NextID3." Each row corresponds to a part of a script for a messaging game, with the "Message" column containing a snippet of the text sent to players, and the "Option" columns indicating the numeric response a player can send. The "NextID" columns point to the ID of the next message in the sequence based on the player's choice. The first row, for example, reads "Welcome to V..." with options 1, 2, and 3 leading to different "NextID" outcomes.Database Setup

Habilitación de la API Notion para el acceso a datos y la integración con Vonage AI Studio

¡Ahora viene la parte divertida! Con la interfaz fácil de usar de Vonage AI Studio, puedes diseñar el flujo de conversación de tu chatbot. Es una configuración de arrastrar y soltar, lo que significa que no necesitas conocimientos de codificación para ponerte en marcha. Puedes agregar diferentes nodos de diálogo y definir respuestas.

Nuestro flujo debería ser así:

The image shows a flowchart for a conversational application, likely in a visual programming environment. It begins with a "Start" node, followed by a "Set Starting Parameter" node that sets a parameter to 1. Next is a "Webhook" node with outcomes for "2XX" (successful response) and "Failed" connected to a "Collect Input" node for text input. There are "Conditions" nodes with options 1, 2, 3, and a check for "Not End," which lead to corresponding "Set Parameter" nodes (1, 2, and 3) that presumably update the query parameter with new values. The flow includes "Exit Points" for when the query ID is not 0 or equals 0, leading to the "End Game" message node, which sends a thank you message, and finally to an "End Conversation" node, which likely signifies the end of the conversation flow.Conversation Flow

Primero, configura Vonage AI Studio.

A continuación, vamos a hacer nodos y propiedades para conectarse entre sí para el flujo de conversación. También puedes descargar el archivo zip de esta muestra e importar el agente en Vonage AI Studio. Si quieres construir esto desde cero, aquí están los nodos que necesitaremos crear y a qué nodos y propiedades necesitamos conectarlos:

Propiedades > Parámetros

Nombre de la propiedad: Set Start Parameter

Crea un parámetro llamado QUERY_PARAMETER y ponlo a 1 ya que nuestro primer ID empieza en 1.

Conexión(es): START (izquierda) y $QUERY_PARAMATER = 1 a Webhook

The image shows a table with two columns labeled "# ID" and "Aa Message." The first row under "# ID" shows the number 1, and adjacent to it under "Aa Message," the text reads "Welcome to Vonage's Gate! Choose a class: (1) Warrior, (2) Mage, or (3) Rogue." This appears to be a snippet from a database used in an interactive text-based game, where the player is prompted to choose a character class at the beginning of the game.Set Start Parameter

NODOS > Integraciones > Webhook

Nombre de nodo: Webhook

Método: POST URL de solicitud: https://api.notion.com/v1/databases/<databaseid>/consulta

Para encontrar el ID de una base de datosNavegue hasta la URL de la base de datos en su espacio de trabajo Notion. El ID es la cadena de caracteres de la URL que se encuentra entre la barra oblicua que sigue al nombre del espacio de trabajo (si procede) y el signo de interrogación. El ID es una cadena alfanumérica de 32 caracteres.

Cabeceras (Cabecera HTTP : Valor)

  • Autorización : Portador $NOTION_ACCESS_TOKEN

  • Notion-Version : 2022-06-28

Para encontrar su $NOTION_ACCESS_TOKENpase por el proceso de autorización para un integración interna interna en Notion.

Cuerpo

Pon el siguiente texto en el cuerpo:

{
 "filter": {
  "property": "ID",
  "unique_id": {
   "equals": $QUERY_PARAMETER
  }
 }
}

Mapa de respuestas

  • Tipo de respuesta: JSON Ruta del objeto

Después de rellenar la información anterior en nuestro nodo webhook, asegúrate de que el webhook está funcionando haciendo clic en el botón 'Test request' en la parte superior derecha. En Respuesta, verás que devuelve todos los datos de nuestra tabla Notion. Usando la respuesta, define la ruta del objeto y asígnala a un parámetro. Si necesitas ayuda, echa un vistazo a mi blog que [profundiza en el mapeo de respuestas](LINK A MI BLOG).

Conexión(es): 2xx para recoger entradas

The image displays a section of a user interface titled "Response Mapping" for a software application, likely related to API or database interaction. It shows a configuration setup for handling JSON responses, with mappings from object paths in the JSON structure to named parameters. For example, "results[0].properties.Message.title[0].plain_text" is mapped to the parameter "$RETURNED_MESSAGE," and similar mappings are made for "Option1," "Option2," "Option3," "NextID1," "NextID2," and "NextID3," each pointing to their respective returned parameters. This setup is used to extract specific pieces of data from a JSON response and assign them to variables within the application  The image shows a graphical user interface for mapping JSON response data to specific parameters within a software application. It lists various JSON object paths such as "results[0].properties.Message.title[0].plain_text" and corresponding parameters like "$RETURNED_MESSAGE". The mapping is designed to translate the structured JSON data into variables that the application can use in its operations.Response Mapping

NODOS > Conversación > Recoger aportaciones

Nombre del nodo: Recoger entradas

Parámetros: ENTRADA

Mensaje de texto: $RETURNED_MESSAGE (deberá escribirlo en lugar de copiar y pegar este texto)

Entrada esperada: Texto

Conexión(es): Texto a condiciones

The image displays a section of a user interface for a "Collect Input" node within a chatbot or automated messaging system. It has a field marked "Parameter" with "INPUT" entered in a text box, outlined in red, indicating the parameter that will be used to store the input collected. Below that, under "Message," there is an option for "Text" selected, and a text box labeled "Prompt" contains a placeholder variable "$RETURNED_MESSAGE" within it, also outlined in red. This setup suggests that the system is configured to prompt the user for input and store their response in the "INPUT" parameter.Collect Input

Nodos > Conversación > Condiciones

Nombre del nodo: Condiciones

Nombre(s) de la condición:

  • Opción 1

    * Parameter: INPUT
    * Operation: Is equal to
    * Value: $RETURNED_OPTION1
  • Opción 2

    * Parameter: INPUT
    * Operation: Is equal to
    * Value: $RETURNED_OPTION2
  • Opción 3

    * Parameter: INPUT
    * Operation: Is equal to
    * Value: $RETURNED_OPTION3
  • No Fin

    * Parameter: RETURNED_ID
    * Operation: Is equal to
    * Value: 9
    
    	_or_
    
    * Parameter: RETURNED_ID
    * Operation: Is not equal to
    * Value: 11
    
    	_or_
    
    * Parameter: RETURNED_ID
    * Operation: Is not equal to
    * Value: 12
    
    	_or_
    
    * Parameter: RETURNED_ID
    * Operation: Is not equal to
    * Value: 15
    
    	_or_
    
    * Parameter: RETURNED_ID
    * Operation: Is not equal to
    * Value: 16
    
    	_or_
    
    * Parameter: RETURNED_ID
    * Operation: Is not equal to
    * Value: 18
    
    	_or_
    
    * Parameter: RETURNED_ID
    * Operation: Is not equal to
    * Value: 19

Conexión(es):

- Opción 1 para ajustar el parámetro 1

- Opción 2 para ajustar el parámetro 2

- Opción 3 para ajustar el parámetro 3

The image shows a part of a software interface under the "NODES" menu, specifically within the "Conversation" section. There are different node options listed: "Classification," "Collect Input," and "Send Message." The "Conditions" node is highlighted with a red outline, indicating it is likely selected or being emphasized for the user to interact with. These nodes represent different functions or processes that can be configured within a conversation flow in a chatbot or similar automated system.Conditions

Propiedades > Parámetros

Nombre de la propiedad: Set Parameter 1

Parámetro: PARÁMETRO_CONSULTA

Valor: $RETURNED_NEXT_ID1

Conexión(es): $QUERY_PARAMETER a Puntos de Salida

Dependiendo de la opción que elija el jugador, esta propiedad apuntará al ID del siguiente mensaje que el jugador debería recibir después de enviar "1".

The image displays a user interface for a "Set Parameter 1" configuration. There are two fields: one labeled "Parameter," with "QUERY_PARAMETER" selected from a dropdown menu, and another labeled "Value," containing the placeholder "$RETURNED_NEXT_ID1." This setup indicates that the system is configured to assign the value from "$RETURNED_NEXT_ID1" to the "QUERY_PARAMETER." This is typically part of a workflow where the value of a parameter is dynamically set based on a previous action or input.Set Parameter 1

Propiedades > Parámetros

Nombre de la propiedad: Set Parameter 2

Parámetro: PARÁMETRO_CONSULTA

Valor: $RETURNED_NEXT_ID2

Conexión(es): $QUERY_PARAMTER a Puntos de Salida

Dependiendo de la opción que elija el jugador, esta propiedad apuntará al ID del siguiente mensaje que el jugador debería recibir después de enviar "2".

Propiedades > Parámetros

Nombre de la propiedad: Set Parameter 3

Parámetro: PARÁMETRO_CONSULTA

Valor: $RETURNED_NEXT_ID3

Conexión(es): $QUERY_PARAMTER a Puntos de Salida

Dependiendo de la opción que elija el jugador, esta propiedad apuntará al ID del siguiente mensaje que el jugador debería recibir después de enviar "3".

Nodos > Conversación > Condiciones

Nombre del nodo: Puntos de salida

Nombre(s) de la condición:

  • QUERY_ID NOT 0

    *Parameter: QUERY_PARAMETER*
    	 Operation: Is not equal to
    	 *Value: 0*
    	 Connection(s): $QUERY_ID NOT 0 to Webhook
  • QUERY_ID = 0

    *Parameter: QUERY_PARAMETER*
    	 Operation: Is equal to
    	 *Value: 0*
    	 Connection(s): $QUERY_ID = 0 to End Game

Nodos > Conversación > Enviar mensaje

Nombre del nodo: End Game

Texto: ¡Gracias por jugar a Vonage's Gate! Comparte tus opiniones en Twitter y etiqueta a @dianasoyster y @VonageDev

Conexión(es): Gracias por jugar a FIN DE LA CONVERSACIÓN

The image shows a section of a user interface with a menu labeled "NODES" and a subsection titled "Conversation." Within this subsection, a list of conversational nodes is presented: "Classification," "Collect Input," and "Send Message." The "Send Message" node is highlighted with a red outline, suggesting it is currently selected or being focused on. These nodes represent different stages or actions in a conversation flow within a chatbot or automated messaging system.Send Message

Este nodo se envía cuando el jugador llega al final de su aventura. Esto significa que todos los valores de la tabla son 0 y envían "1" para continuar como se les pide.

The image is a screenshot of a user interface for a messaging application, showing an "End Game" messaging node. It displays various types of message options such as Text, Image, Audio, File, Location, and Video, with the Text option highlighted. Below the message options, there's a section labeled "Agent says," followed by a text box containing the message: "Thanks for playing Vonage’s Gate! Share your thoughts on Twitter and tag @dianasoyster and @VonageDev." This implies that the agent, or chatbot, will send this message at the end of the game to encourage players to share their experience on Twitter.End Game

Nodos > Acciones > Finalizar conversación

Nombre del nodo: Fin de la conversación

The image depicts a user interface from a software application with a menu titled "Actions" on the left side. One of the actions, "End Conversation," is highlighted within a red outlined box and has an icon resembling a chat bubble with a diagonal line through it, indicating the function to terminate a conversation. Other action options listed but not highlighted include "Send Email," "Send SMS," and "Live Agent Routing," each with their respective icons.End Conversation

Técnicamente, no necesitas este nodo, pero por buena práctica, deberíamos incluirlo.

Pruebas

En la esquina superior derecha de Vonage AI Studio, hay un botón negro de Probador. Haz clic en él para jugar.

This is a screenshot of a text-based role-playing game being played through a chat interface. The game is presumably named "Vonage's Gate." The player is being welcomed by the game's agent and is prompted to choose a class out of Warrior, Mage, or Rogue. The player chooses the option "3" which corresponds to the Rogue class. The agent acknowledges the choice with a poetic description of the Rogue class, highlighting stealth and cunning as their attributes, and instructs the player to send the message "Text 1" to continue the game.Testing the Agent in AI Studio - Part 1

This image shows a continuation of the text-based role-playing game in a chat interface, where the game's agent presents a new scenario to the player. The player is faced with a decision: a mysterious figure has offered a quest to find a lost artifact. The agent asks whether the player wants to (1) accept the quest or (2) decline and explore the town. The player chooses option "1" to accept the quest. In response, the agent congratulates the player for bravely accepting the quest and mentions that the mysterious figure hands the player a worn map with a location marked in red, presumably indicating where the quest will lead.Testing the Agent in AI Studio - Part 2

This image shows the next part of the text-based role-playing game. The game's agent gives the player a choice after they have accepted the quest to venture into the Spiderwood Forest. The player must decide whether to (1) head to the forest right away or (2) stop by the village to gather more information about the forest. The player chooses option "1" to head to the forest right away.  Following this decision, the agent describes the journey into the Spiderwood Forest, indicating that the player has been given a map and warned of dangers ahead. After hours of travel, the player reaches a fork in the path and must choose again: go (1) left, towards the sounds of a river, or (2) right, where the path seems safer. The player's choice at this point is not shown in the image.Testing the Agent in AI Studio - Part 3

The image continues the narrative of the text-based role-playing game. It seems that the player chose to follow the river's sound, which led them to a hidden cave behind a waterfall. Inside the cave, they find the lost artifact, described as glowing with an otherworldly light. The game's agent then presents the player with a new decision: (1) take the artifact, or (2) walk back to the safer path. The player opts for choice "1" to take the artifact. The outcome of this decision is not displayed in the image.Testing the Agent in AI Studio - Part 4

This image shows the conclusion of the text-based role-playing game scenario. The player, having chosen to take the artifact, is told they feel a sense of accomplishment. The game's agent informs the player that they have successfully completed the quest and now have the option to return the artifact to the mysterious figure or keep it for themselves. The player is instructed to text "1" to continue, which they do.  Finally, the game's agent thanks the player for playing "Vonage's Gate" and suggests sharing thoughts on Twitter, providing two handles to tag in the post. The conversation in the game interface then appears to be ended by the agent.Testing the Agent in AI Studio - Part 5

Adéntrate en tu propia aventura

Como se cita en Baldur's Gate 3, "No se puede transigir con el mal. En este tutorial, aprendimos a usar las mejores prácticas cuando almacenamos datos para que no tengas que lidiar con la "malvada" deuda tecnológica en caso de que necesites hacer cambios a tus textos en el futuro. También aprendimos a integrar una base de datos con Vonage AI Studio y Messages API. Si quieres los datos de este ejemplo, no dudes en unirte a nuestra "clase" de desarrolladores en Slack y síguenos en Xantes conocido como Twitter. Si crea una aplicación similar, compártala y etiquétame - Me encantará conocer tu aventura.

Compartir:

https://a.storyblok.com/f/270183/384x384/b68093ec17/diana-pham.png
Diana PhamDefensor del Desarrollador

Diana es desarrolladora de Vonage. Le gusta comer ostras frescas.