How to Create a Text Adventure Game with OpenAI Playground

Text Adventure Game

Whether you’re a beginner in programming or an experienced developer, creating a text adventure game can be a fun and educational project. In this tutorial, we will explore how to create a text adventure game using OpenAI Playground, a powerful platform that allows you to build interactive AI models.

Text adventure games, also known as interactive fiction, are games predominantly based on textual descriptions where users interact with the game world by typing commands. These games offer a unique storytelling experience. Thanks to OpenAI Playground, you can easily create one without worrying about underlying infrastructure and model training.

Prerequisites

To follow along with this tutorial, you will need:

  • Basic knowledge of programming concepts
  • A modern web browser
  • An internet connection

Step 1: Getting Started with OpenAI Playground

OpenAI Playground is a browser-based platform that allows you to create, train, and deploy AI models interactively. It provides a coding interface, a training environment, and model deployment capabilities.

To start, open your preferred web browser and navigate to the OpenAI Playground website at playground.openai.com.

OpenAI Playground Homepage

You will be greeted with the OpenAI Playground homepage, which showcases various example projects and demos. We will create our own project from scratch, so click on the “New Project” button at the top right corner of the page.

Step 2: Creating a Text Adventure Game Project

In the project creation form, provide a suitable name for your project, such as “Text Adventure Game.” You can also provide a brief description if desired. Choose the “Text” option in the “Problem Type” field since we will be working with a text-based game.

Create Project Form

After filling out the required fields, click on the “Create Project” button.

Step 3: Defining the Game’s User Interface

Once your project is created, you will be redirected to the project workspace. This workspace includes three sections: the code editor on the left, the model output in the center, and the user input on the right.

To define the user interface of our text adventure game, we need to add some basic HTML elements to the project’s code editor.

In the code editor, start by removing the existing code and add the following HTML structure:

<!DOCTYPE html>
<html>
  <head>
    <style>
      #game-container {
        padding: 20px;
      }

      #output-container {
        border: 1px solid #ddd;
        padding: 10px;
        margin-bottom: 10px;
        min-height: 200px;
      }
    </style>
  </head>
  <body>
    <div id="game-container">
      <div id="output-container"></div>
      <input
        type="text"
        id="user-input"
        placeholder="Enter your command..."
        onkeydown="handleKeyDown(event)"
      />
    </div>

    <script>
      function handleKeyDown(event) {
        if (event.key === "Enter") {
          handleUserInput();
        }
      }

      function handleUserInput() {
        const userInput = document.getElementById("user-input").value;
        document.getElementById("output-container").textContent = `> ${userInput}`;
        document.getElementById("user-input").value = "";
      }
    </script>
  </body>
</html>

In this code, we define a container div with the id “game-container” that holds our game’s user interface elements. Inside the container, we have a div with the id “output-container” that will display the game’s output messages. Below the output container, we have an input field, represented by the HTML input element, with the id “user-input” to capture user commands.

You’ll notice two JavaScript functions at the end: handleKeyDown and handleUserInput. The handleKeyDown function listens for the “Enter” key press event, and if it detects it, it calls the handleUserInput function.

The handleUserInput function retrieves the user’s input, clears the input field, and displays the entered command in the output container.

Click on the “Save” button at the top right corner of the page to save your changes.

Step 4: Defining the Game Logic

Now that we have our basic user interface, we need to define the logic that powers our text adventure game. In this tutorial, we will create a simple game where the player is exploring a haunted house.

First, let’s initialize the game state by adding the following JavaScript code before the handleKeyDown and handleUserInput functions:

let gameState = {
  room: "entry",
  visitedRooms: ["entry"],
};

The gameState object keeps track of the current room and the rooms the player has visited.

Next, inside the handleUserInput function, add the following code to process the user’s commands:

function handleUserInput() {
  const userInput = document.getElementById("user-input").value.trim().toLowerCase();

  let outputMessage = "";

  if (userInput === "help") {
    outputMessage = "Available commands: go, look, help";
  } else if (userInput.startsWith("go ")) {
    const roomId = userInput.split(" ")[1];
    if (isValidRoom(roomId)) {
      outputMessage = `You entered the ${roomId} room.`;
      gameState.room = roomId;
      if (!gameState.visitedRooms.includes(roomId)) {
        gameState.visitedRooms.push(roomId);
      }
    } else {
      outputMessage = `Invalid room: ${roomId}.`;
    }
  } else if (userInput === "look") {
    outputMessage = describeRoom(gameState.room);
  } else {
    outputMessage = "Invalid command. Type 'help' for available commands.";
  }

  document.getElementById("output-container").textContent += `n> ${userInput}n${outputMessage}`;
  document.getElementById("user-input").value = "";
}

In this code, we first clean up the user’s input by removing any leading or trailing whitespace and converting it to lowercase. Then, we define an outputMessage variable that will store the text to be displayed in response to the user’s command.

The logic checks for different command keywords. If the user types “help”, it displays a list of available commands. If the user types “go” followed by a room name, it checks if the room is valid using the isValidRoom function and updates the game state accordingly. If the user types “look”, it displays the description of the current room using the describeRoom function. If the user types an invalid command, it displays an error message.

Notice that the outputMessage is appended to the output container contents using the += operator. This ensures that the previous game output is preserved.

Before we proceed, let’s add two helper functions: isValidRoom and describeRoom. Add the following code after the handleUserInput function:

function isValidRoom(roomId) {
  const validRooms = ["entry", "living room", "kitchen", "bedroom"];
  return validRooms.includes(roomId);
}

function describeRoom(roomId) {
  switch (roomId) {
    case "entry":
      return "You are standing in the entry hallway. There are doors to the living room and kitchen.";

    case "living room":
      return "You enter the spooky living room. There is a large fireplace and an old dusty piano.";

    case "kitchen":
      return "You step into the creepy kitchen. The air is stale and the countertops are covered in cobwebs.";

    case "bedroom":
      return "You found the haunted bedroom. There is an eerie presence that sends shivers down your spine.";

    default:
      return "";
  }
}

The isValidRoom function checks if a given room is valid by comparing it against a list of known room names.

The describeRoom function returns a description of the room based on the given roomId.

Step 5: Adding a Winning Condition

Let’s add a winning condition to our game. For this example, we’ll consider reaching the bedroom as the winning condition.

First, update the handleUserInput function to add a check for the winning condition:

if (userInput === "look") {
  outputMessage = describeRoom(gameState.room);

  if (gameState.room === "bedroom") {
    outputMessage += "nnCongratulations! You have reached the haunted bedroom. You win!";
    document.getElementById("user-input").disabled = true;
  }
}

We added an additional check after displaying the room description to see if the player is in the “bedroom”. If the player is in the bedroom, we add a congratulatory message to the outputMessage and disable the user input field by setting disabled attribute to true.

Step 6: Testing Your Text Adventure Game

Now that our game logic is complete, it’s time to test our text adventure game in the OpenAI Playground.

To run the game, click on the “Play” button at the top right corner of the page. This will open a new tab with your game.

You can now interact with the game by typing commands into the input field. Try some basic commands like “look” and “help” to verify that the logic is working as expected.

Text Adventure Game Output

If everything is functioning correctly, try navigating between different rooms by using the “go” command followed by a room name. For example, you can try typing “go living room” to move to the living room.

Text Adventure Game Navigation

Once you reach the bedroom, you should see the congratulations message and the input field should become disabled.

Step 7: Customizing and Expanding Your Game

Congratulations on building your own text adventure game using OpenAI Playground! You can now customize and expand your game by adding more rooms, puzzles, items, or any other elements to enhance the gameplay experience.

Here are a few ideas to get you started:

  • Create additional rooms with unique descriptions and properties.
  • Implement puzzles or riddles that the player needs to solve to progress.
  • Add items in rooms that the player can use or collect.
  • Include non-player characters (NPCs) with whom the player can interact.
  • Incorporate branching narratives and multiple endings based on player decisions.

Feel free to modify the existing code or come up with your own ideas to make your game even more exciting and engaging.

Conclusion

In this tutorial, you learned how to create a text adventure game using OpenAI Playground. With its user-friendly interface, you were able to define the game’s user interface, implement the game logic, and add a winning condition. You also explored testing and customizing your game to make it more personalized and interactive.

Text adventure games offer a great way to explore game development, build your coding skills, and unleash your creativity. OpenAI Playground empowers you to create interactive AI models and prototypes without worrying about infrastructure, allowing you to focus on the fun part: building your game.

Have fun expanding your text adventure game and happy coding!

Related Post