https://a.storyblok.com/f/270183/93924/cdfb6a5b00/rpg_ai-studio-notion.png

Como criar um jogo de RPG com o Vonage AI Studio e o Notion

Publicado em January 24, 2024

Tempo de leitura: 7 minutos

De jogar RPGs à criação do Gate da Vonage

Quando eu era mais jovem, parte do meu tempo de lazer era preenchido por videogames que recebia de herança — verdadeiras joias por si só, mas com os quais, admito, passava tempo demais, o que muitas vezes me rendia uma ou duas broncas. Eu gostava de vários tipos de jogos, desde simulações sociais e jogos de plataforma até jogos de tiro em primeira pessoa e meus favoritos, os jogos de RPG (role-playing games). Sem que eu percebesse na época, cada hora que passava nesses mundos de fantasia estava, sutilmente, aprimorando minhas habilidades de resolução de problemas e minha criatividade. Avançando no tempo, foram justamente essas aventuras nos jogos que lançaram as bases para este blog.

No ano passado, a Larian Studios lançou Baldur's Gate 3, um RPG baseado no jogo de tabuleiro Dungeon & Dragons. Pense em um RPG como mergulhar em um livro onde, em vez de apenas ler a história, você se torna o personagem principal. Você vai passar por aventuras, tomar decisões, interagir com outros personagens e moldar o desfecho da história com base nas suas escolhas. É uma chance de vivenciar uma narrativa de forma interativa, em que o mundo reage ao que você decide.

Eu mesmo joguei o jogo e fiquei profundamente impressionado com o quão única e envolvente era a experiência de cada jogador, já que seguia o estilo “escolha sua própria aventura”. Então, senti-me motivado a recriar uma versão mais simples de um RPG usando o Vonage AI Studio e Messages API — o Gate da Vonage!

Criando um RPG com mensagens

Veja como vamos criar uma experiência narrativa em que os jogadores decidem o destino de seus personagens. Agora, concentre-se no seu personagem principal e vamos começar a criar!

Pré-requisitos

Configuração do banco de dados e do jogo

Como prática recomendada, armazenaremos todos os valores utilizados na jogabilidade em um banco de dados — para este exemplo, usaremos o Notion!

Como usar o Notion como banco de dados

É uma opção fácil de usar, não exige conhecimentos avançados de banco de dados e é superprático, pois as alterações aparecem instantaneamente — perfeito para manter nosso conteúdo atualizado e responsivo. Embora seja menos escalável do que os bancos de dados tradicionais, ele dá conta de tudo o que precisamos para este aplicativo. A melhor parte é que ele se integra facilmente ao Vonage AI Studio e a outras plataformas de baixo código, facilitando muito a nossa vida!

Crie sua planilha

Acesse Notion. Clique no botão (+) para adicionar uma página. Na nova página, na seção BANCO DE DADOS, clique em “Tabela”. Crie as seguintes colunas:

  • ID (tipo: número) — o ID da mensagem é enviado por MMS

  • Mensagem (tipo: título) — o texto propriamente dito enviado

  • Opção 1 (tipo: número) — a resposta que um jogador envia ao escolher a opção 1

  • Opção 2 (tipo: número) — a resposta que um jogador envia ao escolher a opção 2

  • Opção 3 (tipo: número) — a resposta que um jogador envia ao escolher a opção 3

  • NextID1 (tipo: número) — o ID da próxima mensagem que o jogador recebe após escolher a opção 1

  • NextID2 (tipo: número) — o ID da próxima mensagem que o jogador recebe após escolher a opção 2

  • NextID3 (tipo: número) — o ID da próxima mensagem que o jogador recebe após escolher a opção 3

Como estruturar seu jogo

Você pode personalizar o enredo da maneira que quiser. Na minha história, o jogador acaba ficando com o artefato. As mensagens enviadas ao jogador são acionadas pelas respostas dele à mensagem anterior.

Criação de Personagem

  • Mensagem inicial: Envie uma breve apresentação e uma opção simples para a criação do personagem.

No meu banco de dados, dá para ver que o ID 1 exibe a mensagem inicial: “Bem-vindo ao Portão da Vonage! Escolha uma classe: (1) Guerreiro, (2) Mago ou (3) Ladino.”

  • Confirmação do personagem: Assim que eles responderem com uma escolha, envie uma confirmação com uma breve descrição do personagem.

Progressão no jogo

Imediatamente após a confirmação do personagem, apresente o primeiro cenário simples que exija uma decisão. Quando o jogador fizer uma escolha, responda com um breve resultado e outro ponto de decisão. Continue com uma série de pontos de decisão simples que mantenham a história em andamento sem exigir interações complexas. Para esta demonstração, faremos com que os jogadores respondam com mensagens de um único caractere. Após algumas rodadas de decisões, podemos encerrar a demonstração com um final simples.

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

Ativação da API do Notion para acesso a dados e integração com o Vonage AI Studio

Agora vem a parte divertida! Com a interface fácil de usar do Vonage AI Studio, você pode criar o fluxo de conversação do seu chatbot. A configuração é feita por arrastar e soltar, o que significa que você não precisa ter conhecimentos de programação para começar. Você pode adicionar diferentes nós de diálogo e definir respostas.

Nosso fluxo deve ficar assim:

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

Primeiro, configure o Vonage AI Studio.

A seguir, vamos criar nós e propriedades para conectá-los entre si, a fim de definir o fluxo da conversa. Você também pode baixar o arquivo zip deste exemplo e importar o agente no Vonage AI Studio. Se você quiser construir isso do zero, aqui estão os nós que precisaremos criar e quais nós e propriedades precisamos conectar a eles:

Propriedades > Parâmetros

Nome da propriedade: Definir parâmetro inicial

Crie um parâmetro chamado QUERY_PARAMETER e defina-o como 1, já que nosso primeiro ID começa em 1.

Conexão(ões): START (à esquerda) e $QUERY_PARAMATER = 1 para o 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

NODES > Integrações > Webhook

Nome do nó: Webhook

Método: POST URL da solicitação: https://api.notion.com/v1/databases/<databaseid>/query

Para encontrar o ID de um banco de dados, acesse a URL do banco de dados no seu espaço de trabalho do Notion. O ID é a sequência de caracteres na URL que fica entre a barra após o nome do espaço de trabalho (se houver) e o ponto de interrogação. O ID é uma sequência alfanumérica de 32 caracteres.

Cabeçalhos (Cabeçalho HTTP: Valor)

  • Autorização: Portador $NOTION_ACCESS_TOKEN

  • Versão do Notion: 28/06/2022

Para obter seu $NOTION_ACCESS_TOKEN, siga o processo de autorização para um integração interna no Notion.

Corpo

Coloque o seguinte texto no corpo:

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

Mapeamento de respostas

  • Tipo de resposta: Caminho do objeto JSON

Depois de preencher as informações acima em nosso nó de webhook, verifique se o webhook está funcionando clicando no botão “Testar solicitação”, no canto superior direito. Na seção “Resposta”, você verá que ele retorna todos os dados da nossa tabela do Notion. Usando a resposta, defina o caminho do objeto e mapeie-o para um parâmetro. Se precisar de ajuda, confira meu blog, que [aborda o mapeamento de respostas com mais detalhes](LINK PARA MEU BLOG).

Conexão(ões): 2xx para coletar dados de entrada

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

NÓS > Conversa > Coletar opiniões

Nome do nó: Coletar entrada

Parâmetro: ENTRADA

Texto de prompt: $RETURNED_MESSAGE (talvez seja necessário digitar isso manualmente, em vez de copiar e colar este texto)

Entrada esperada: Texto

Conexão(ões): Texto para Condições

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

Nós > Conversa > Condições

Nome do nó: Condições

Nome(s) da(s) condição(ões):

  • Opção 1

    * Parameter: INPUT
    * Operation: Is equal to
    * Value: $RETURNED_OPTION1
  • Opção 2

    * Parameter: INPUT
    * Operation: Is equal to
    * Value: $RETURNED_OPTION2
  • Opção 3

    * Parameter: INPUT
    * Operation: Is equal to
    * Value: $RETURNED_OPTION3
  • Não é o fim

    * 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

Conexão(ões):

- Opção 1 para definir o parâmetro 1

- Opção 2 para definir o parâmetro 2

- Opção 3 para definir o 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

Propriedades > Parâmetros

Nome da propriedade: Definir parâmetro 1

Parâmetro: QUERY_PARAMETER

Valor: $RETURNED_NEXT_ID1

Conexão(ões): $QUERY_PARAMETER aos pontos de saída

Dependendo da opção escolhida pelo jogador, essa propriedade indicará o ID da próxima mensagem que o jogador deverá receber após 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

Propriedades > Parâmetros

Nome da propriedade: Definir parâmetro 2

Parâmetro: QUERY_PARAMETER

Valor: $RETURNED_NEXT_ID2

Conexão(ões): $QUERY_PARAMTER aos pontos de saída

Dependendo da opção escolhida pelo jogador, essa propriedade indicará o ID da próxima mensagem que o jogador deverá receber após enviar “2”.

Propriedades > Parâmetros

Nome da propriedade: Definir parâmetro 3

Parâmetro: QUERY_PARAMETER

Valor: $RETURNED_NEXT_ID3

Conexão(ões): $QUERY_PARAMTER aos pontos de saída

Dependendo da opção escolhida pelo jogador, essa propriedade indicará o ID da próxima mensagem que o jogador deverá receber após enviar “3”.

Nós > Conversa > Condições

Nome do nó: Pontos de saída

Nome(s) da(s) condição(ões):

  • QUERY_ID NÃO É 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

Nós > Conversa > Enviar mensagem

Nome do nó: End Game

Texto: Obrigado por jogar o Gate da Vonage! Compartilhe sua opinião no Twitter e marque @dianasoyster e @VonageDev

Conexão(ões): Obrigado por jogar. FIM DA CONVERSA

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 nó é enviado depois que o jogador chega ao fim de sua aventura. Isso significa que todos os valores da tabela são 0 e ele envia um “1” para continuar, conforme solicitado.

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

Nós > Ações > Encerrar conversa

Nome do nó: Encerrar conversa

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

Tecnicamente, você não precisa desse nó, mas, por uma questão de boas práticas, devemos incluí-lo.

Testes

No canto superior direito do Vonage AI Studio, há um botão preto chamado “Tester”. Clique nele para jogar.

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

Embarcando na sua própria aventura

Conforme citado em Baldur’s Gate 3: “Não se pode fazer concessões ao mal. No fim das contas, ele sempre sai ganhando.” Neste tutorial, aprendemos como aplicar as melhores práticas ao armazenar dados, para que você não precise lidar com a “maligna” dívida técnica caso precise fazer alterações em seus textos no futuro. Também aprendemos a integrar um banco de dados com o Vonage AI Studio e a Messages API. Se você quiser os dados deste exemplo, fique à vontade para participar da nossa “turma” de desenvolvedores no Slack e nos seguir no X, antes conhecido como Twitter. Se você criar uma aplicação semelhante, compartilhe-a e me marque — adoraria saber mais sobre sua aventura!

Compartilhar:

https://a.storyblok.com/f/270183/384x384/b68093ec17/diana-pham.png
Diana PhamRepresentante de Desenvolvedores

Diana é defensora de desenvolvedores na Vonage. Ela gosta de comer ostras frescas.