Horje
Building a Text-Based Adventure Game with SpaCy: A Step-by-Step Tutorial

In this article, we’ll explore how to create a simple text-based adventure game using Python’s SpaCy library for natural language processing (NLP). This game will allow players to navigate through different paths in a fictional forest, making choices that influence the outcome of their adventure.

Key Concepts to Discuss Before Implementation

1. Natural Language Processing (NLP):

  • Definition: NLP is a field of artificial intelligence that focuses on the interaction between computers and humans through natural language. It involves tasks such as text analysis, language generation, and semantic understanding.
  • Relevance: In our game, NLP helps parse player inputs and interpret commands like “north,” “inspect,” or “swim,” making the game interactive and user-friendly.

2. SpaCy Library:

  • Definition: SpaCy is an open-source NLP library in Python designed for efficient and accurate text processing. It offers pre-trained models for various NLP tasks, including tokenization, lemmatization, and part-of-speech tagging.
  • Relevance: We’ll use SpaCy to process and understand player inputs, which are essential for guiding the game’s flow.

3. Game Design:

  • Definition: Game design involves creating the rules, scenarios, and mechanics that define how a game functions and engages players.
  • Relevance: Designing the game includes defining the paths, possible actions, and outcomes, ensuring a balanced and enjoyable experience for players.

4. Class-Based Design:

  • Definition: In object-oriented programming, a class is a blueprint for creating objects that encapsulate data and methods.
  • Relevance: Using classes allows us to encapsulate the game state, methods for processing inputs, and different paths in a structured way.

Implementing Text-Based Adventure Game with SpaCy

Step 1: Importing Libraries

Import the necessary libraries for the game. In this case, the spacy library is used for natural language processing to parse user inputs.

import spacy

Step 2: Define the Game Class

Define the Game class which contains all the methods and attributes related to the game.

class Game:
    def __init__(self):
        self.state = "start"
        self.nlp = spacy.load("en_core_web_sm")

Step 3: Initialize the Game

The __init__ method initializes the game state to "start" and loads the spaCy model for processing user inputs.

def __init__(self):
    self.state = "start"
    self.nlp = spacy.load("en_core_web_sm")

Step 4: Parse User Input

Define the parse_input method to process user inputs using spaCy to identify key actions like directions and commands.

def parse_input(self, input_text):
    doc = self.nlp(input_text)
    for token in doc:
        if token.lemma_ in ['north', 'east', 'west', 'south', 'inspect', 'ignore', 'explore', 'avoid', 'swim', 'build', 'enter', 'move']:
            return token.lemma_
    return None

Step 5: Start the Game

Define the start method to initialize the game, prompt the player for directions, and handle the player’s choice by calling the appropriate method.

def start(self):
    print("You are an adventurer on a quest to find a legendary treasure hidden deep within an ancient forest.")
    print("You stand at the entrance of the forest, with paths leading to the north, east, west, and south.")
    choice = self.parse_input(input("Which way do you go? (north, east, west, south): ").strip().lower())
    if choice == 'north':
        self.state = "north"
        self.north_path()
    elif choice == 'east':
        self.state = "east"
        self.east_path()
    elif choice == 'west':
        self.state = "west"
        self.west_path()
    elif choice == 'south':
        self.state = "south"
        self.south_path()
    else:
        print("Invalid choice. Try again.")
        self.start()

Step 6: Handle the North Path

Define the north_path method to handle the player’s actions when they choose the north path. It prompts for further actions and handles the outcome based on user input.

def north_path(self):
    print("You head north and encounter a colossal ancient oak tree that radiates a mysterious aura.")
    print("Do you inspect the tree or ignore it and continue your journey?")
    choice = self.parse_input(input("Type 'inspect' or 'ignore': ").strip().lower())
    if choice == 'inspect':
        print("You find a magical fruit that grants you immense strength. You continue your journey with newfound power!")
        self.end_game("win")
    elif choice == 'ignore':
        print("A cursed spirit emerges from the tree and haunts you. You run away in fear, abandoning your quest.")
        self.end_game("lose")
    else:
        print("Invalid choice. Try again.")
        self.north_path()

Step 7: Handle the East Path

Define the east_path method to handle the player’s actions when they choose the east path. Similar to the north path, it prompts for further actions and determines the outcome.

def east_path(self):
    print("You head east and discover an abandoned village with eerie silence all around.")
    print("Do you explore the village or avoid it and move on?")
    choice = self.parse_input(input("Type 'explore' or 'avoid': ").strip().lower())
    if choice == 'explore':
        print("You trigger a hidden trap and fall into a pit. Your quest ends here.")
        self.end_game("lose")
    elif choice == 'avoid':
        print("A helpful villager appears and guides you to a safe path through the forest. You continue your journey.")
        self.end_game("win")
    else:
        print("Invalid choice. Try again.")
        self.east_path()

Step 8: Handle the West Path

Define the west_path method to handle the player’s actions when they choose the west path. This method also prompts for further actions and decides the outcome based on user input.

def west_path(self):
    print("You head west and reach a raging river that blocks your path.")
    print("Do you swim across the river or build a raft to float over?")
    choice = self.parse_input(input("Type 'swim' or 'build': ").strip().lower())
    if choice == 'swim':
        print("The current is too strong, and you drown. Your quest ends here.")
        self.end_game("lose")
    elif choice == 'build':
        print("You successfully build a raft and cross the river safely. You continue your journey.")
        self.end_game("win")
    else:
        print("Invalid choice. Try again.")
        self.west_path()

Step 9: Handle the South Path

Define the south_path method to handle the player’s actions when they choose the south path. It prompts for user input and determines the outcome of the game based on their choice.

def south_path(self):
    print("You head south and find the entrance to a dark cave, rumored to hold the legendary treasure.")
    print("Do you enter the cave or move on?")
    choice = self.parse_input(input("Type 'enter' or 'move': ").strip().lower())
    if choice == 'enter':
        print("You bravely enter the cave and find the legendary treasure! You are victorious!")
        self.end_game("win")
    elif choice == 'move':
        print("You decide it's too dangerous and leave. Your quest ends here.")
        self.end_game("lose")
    else:
        print("Invalid choice. Try again.")
        self.south_path()

Step 10: End the Game

Define the end_game method to display the outcome of the game (win or lose) and offer the option to play again.

def end_game(self, result):
    if result == "win":
        print("Congratulations! You have completed your quest successfully!")
    else:
        print("Game Over. Better luck next time.")
    self.play_again()

Step 11: Offer to Play Again

Define the play_again method to ask the player if they want to play the game again and restart the game if they choose “yes”.

def play_again(self):
    choice = input("Do you want to play again? (yes/no): ").strip().lower()
    if choice == 'yes':
        self.start()
    else:
        print("Thank you for playing! Goodbye.")

Step 12: Instantiate and Start the Game

Create an instance of the Game class and start the game by calling the start method.

game = Game()
game.start()

Complete Code

Python
import spacy

class Game:
    def __init__(self):
        self.state = "start"
        self.nlp = spacy.load("en_core_web_sm")

    def parse_input(self, input_text):
        doc = self.nlp(input_text)
        for token in doc:
            if token.lemma_ in ['north', 'east', 'west', 'south', 'inspect', 'ignore', 'explore', 'avoid', 'swim', 'build', 'enter', 'move']:
                return token.lemma_
        return None

    def start(self):
        print("You are an adventurer on a quest to find a legendary treasure hidden deep within an ancient forest.")
        print("You stand at the entrance of the forest, with paths leading to the north, east, west, and south.")
        choice = self.parse_input(input("Which way do you go? (north, east, west, south): ").strip().lower())
        if choice == 'north':
            self.state = "north"
            self.north_path()
        elif choice == 'east':
            self.state = "east"
            self.east_path()
        elif choice == 'west':
            self.state = "west"
            self.west_path()
        elif choice == 'south':
            self.state = "south"
            self.south_path()
        else:
            print("Invalid choice. Try again.")
            self.start()

    def north_path(self):
        print("You head north and encounter a colossal ancient oak tree that radiates a mysterious aura.")
        print("Do you inspect the tree or ignore it and continue your journey?")
        choice = self.parse_input(input("Type 'inspect' or 'ignore': ").strip().lower())
        if choice == 'inspect':
            print("You find a magical fruit that grants you immense strength. You continue your journey with newfound power!")
            self.end_game("win")
        elif choice == 'ignore':
            print("A cursed spirit emerges from the tree and haunts you. You run away in fear, abandoning your quest.")
            self.end_game("lose")
        else:
            print("Invalid choice. Try again.")
            self.north_path()

    def east_path(self):
        print("You head east and discover an abandoned village with eerie silence all around.")
        print("Do you explore the village or avoid it and move on?")
        choice = self.parse_input(input("Type 'explore' or 'avoid': ").strip().lower())
        if choice == 'explore':
            print("You trigger a hidden trap and fall into a pit. Your quest ends here.")
            self.end_game("lose")
        elif choice == 'avoid':
            print("A helpful villager appears and guides you to a safe path through the forest. You continue your journey.")
            self.end_game("win")
        else:
            print("Invalid choice. Try again.")
            self.east_path()

    def west_path(self):
        print("You head west and reach a raging river that blocks your path.")
        print("Do you swim across the river or build a raft to float over?")
        choice = self.parse_input(input("Type 'swim' or 'build': ").strip().lower())
        if choice == 'swim':
            print("The current is too strong, and you drown. Your quest ends here.")
            self.end_game("lose")
        elif choice == 'build':
            print("You successfully build a raft and cross the river safely. You continue your journey.")
            self.end_game("win")
        else:
            print("Invalid choice. Try again.")
            self.west_path()

    def south_path(self):
        print("You head south and find the entrance to a dark cave, rumored to hold the legendary treasure.")
        print("Do you enter the cave or move on?")
        choice = self.parse_input(input("Type 'enter' or 'move': ").strip().lower())
        if choice == 'enter':
            print("You bravely enter the cave and find the legendary treasure! You are victorious!")
            self.end_game("win")
        elif choice == 'move':
            print("You decide it's too dangerous and leave. Your quest ends here.")
            self.end_game("lose")
        else:
            print("Invalid choice. Try again.")
            self.south_path()

    def end_game(self, result):
        if result == "win":
            print("Congratulations! You have completed your quest successfully!")
        else:
            print("Game Over. Better luck next time.")
        self.play_again()

    def play_again(self):
        choice = input("Do you want to play again? (yes/no): ").strip().lower()
        if choice == 'yes':
            self.start()
        else:
            print("Thank you for playing! Goodbye.")

game = Game()
game.start()

Output:

You are an adventurer on a quest to find a legendary treasure hidden deep within an ancient forest.
You stand at the entrance of the forest, with paths leading to the north, east, west, and south.
Which way do you go? (north, east, west, south): north 
You head north and encounter a colossal ancient oak tree that radiates a mysterious aura.
Do you inspect the tree or ignore it and continue your journey?
Type 'inspect' or 'ignore': inspect
You find a magical fruit that grants you immense strength. You continue your journey with newfound power!
Congratulations! You have completed your quest successfully!
Do you want to play again? (yes/no): no 
Thank you for playing! Goodbye.

Conclusion

In this article, we developed a text-based adventure game using Python and SpaCy. We covered the essential concepts, including NLP, the SpaCy library, game design, and class-based programming. By following the outlined steps, we implemented a game that allows players to make choices and experience different outcomes. This project demonstrates how NLP can be applied in interactive applications and provides a foundation for more complex text-based games.




Reffered: https://www.geeksforgeeks.org


AI ML DS

Related
How to Chunk Text Data: A Comparative Analysis How to Chunk Text Data: A Comparative Analysis
Extracting Information By Machine Learning Extracting Information By Machine Learning
Plotting Multiple X-Axes Using Plotly Plotting Multiple X-Axes Using Plotly
Left-Brain AI vs. Right-Brain AI Left-Brain AI vs. Right-Brain AI
Adding progress bar or percentage to tune function in R Adding progress bar or percentage to tune function in R

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
26