Как написать текстовый квест на python

Я в этом особо не шарю, но попробовал сделать хоть что-то. Данный пост для новичков, которые заинтересованы данной темой, но не понимают, что надо делать.

Для начала нам нужен randint.

from random import randint

Теперь можем сделать классы.

class Player:
    hp = 100
    damage = 10

# Записываем в переменную, чтобы было удобно.
p = Player()

class Enemy:
    # Рандомно получает хп врага от 70 до 130, рандомно получает дамаг врага от 6 до 13.
    hp = randint(70,130)
    damage = randint(6,13)

# Записываем в переменную, чтобы было удобно.
e = Enemy()

Пожалуй, можно сделать меню.

def menu(p):
    while True:
        print("1) Сражаться")
        print("2) Посмотреть статистику")
        # try и except просто фиксят ошибки. Не обращайте внимания.
        try:
            n = input("Введите число: ")

            if n == 1:
                menu_fight(p)
            if n == 2:
                menu_stats(p)
            else:
                print("Чего ждем?")

        except NameError:
            print("Введите число")
        except SyntaxError:
            print("Введите число")

Статистика тоже не помешает.

def menu_stats(p):
    print("Статистика игрока")
    print("*****************")
    # Попробую обьяснить, что значит %s. Она по последовательности списка вписывает в %s переменную.
    print("hp {p.hp}")
    print("damage: {p.damage}")
    input("Нажмите Enter для продолжения.")

Теперь потруднее, нужно сделать сражение.

def menu_fight(p):
    while e.hp > 0:
        # Также, как я и сказал по последовательности списка расставляет переменные.
        print(f"Вы hp: {p.hp} damage: {p.damage}")
        print(f"Враг hp: {e.hp} damage: {e.damage}")
        print("**********************")
        print("1)Ударить")
        print("2)Хил 0-5")
        n = input("Введите число: ")
        if n == 1:
            # Здоровье врага отнимает от вашего дамага.
            e.hp -= p.damage
            print("Вы ударили противника, у него осталось %s hp")%(e.hp)
            # Здоровье игрока отнимает от дамага врага.
            p.hp -= e.damage
            print("Противник ударил вас, у вас осталось %s hp")%(p.hp)

            print("*********************")

        if n == 2:
            # Рандомно от 0 до 5 добавляет хп.
            p.hp += randint(0,5)
            # Если здоровье игрока больше, то хп игрока будет равна 100.
            if p.hp > 100:
                p.hp = 100

            print("Ваши хп %s")%(p.hp)

        else:
             print("Чего ждем?")
        if p.hp < 0:
            print("Вы проиграли")
        if e.hp < 0:
            print("Вы победили")

        print("******************")

Под конец осталось просто вызвать меню.

# Вызов меню.
menu(p)

Полный код

from random import randint

class Player:
    hp = 100
    damage = 10

# Записываем в переменную, чтобы было удобно.
p = Player()

class Enemy:
    # Рандомно получает хп врага от 70 до 130, рандомно получает дамаг врага от 6 до 13.
    hp = randint(70,130)
    damage = randint(6,13)

# Записываем в переменную, чтобы было удобно.
e = Enemy()

def menu(p):
    while True:
        print("1) Сражаться")
        print("2) Посмотреть статистику")
        # try и except просто фиксят ошибки. Не обращайте внимания.
        try:
            n = input("Введите число: ")

            if n == 1:
                menu_fight(p)
            if n == 2:
                menu_stats(p)
            else:
                print("Чего ждем?")

        except NameError:
            print("Введите число")
        except SyntaxError:
            print("Введите число")

def menu_stats(p):
    print("Статистика игрока")
    print("*****************")
    # Попробую обьяснить, что значит %s. Она по последовательности списка вписывает в %s переменную.
    print("hp %s."%(p.hp))
        print(f"Вы hp: {p.hp} damage: {p.damage}")
    print("damage %s."%(p.damage))
    input("Нажмите Enter для продолжения.")

def menu_fight(p):
    while e.hp > 0:
        # Также, как я и сказал по последовательности списка расставляет переменные.
        print("Вы hp: %s damage: %s")%(p.hp, p.damage)
        print("Враг hp: %s damage: %s")%(e.hp, e.damage)
        print("**********************")
        print("1)Ударить")
        print("2)Хил 0-5")
        n = input("Введите число: ")
        if n == 1:
            # Здоровье врага отнимает от вашего дамага.
            e.hp -= p.damage
            print("Вы ударили противника, у него осталось %s hp")%(e.hp)
            # Здоровье игрока отнимает от дамага врага.
            p.hp -= e.damage
            print("Противник ударил вас, у вас осталось %s hp")%(p.hp)

            print("*********************")

        if n == 2:
            # Рандомно от 0 до 5 добавляет хп.
            p.hp += randint(0,5)
            # Если здоровье игрока больше, то хп игрока будет равна 100.
            if p.hp > 100:
                p.hp = 100

            print("Ваши хп %s")%(p.hp)

        else:
             print("Чего ждем?")
        if p.hp < 0:
            print("Вы проиграли")
        if e.hp < 0:
            print("Вы победили")

        print("******************")

# Вызов меню.
menu(p)

Спасибо, что прочитали. Можете дать советы, мне будет интересно почитать.

Hello, there fellow learner! Today we are going to make a fun text-based adventure game from scratch. First, let’s understand what a text-based game and then we will implement the same in the python programming language.

What is a text-based game?

A text-based game is a completely text-based input-output simple game. In such type of game, users have options to handle various situations as they arrive with choices taken by the user in the form of inputs.

The storyline for our game

The figure below displays the small story we will be building in python in this tutorial. You can expand or change the story according to your own preferences.

text-based adventure game
Text Based Story Game

Implementation of the Text-Based Adventure Game in Python

Let’s first start off the story by printing the initial scene and how the story moves forward. This can be done by simply using the print function. To make it more fun we can add emoticons and emojis as well!

print("""WELCOME TO THE ADVENTURE GAME!
    Let's start the action! ☆-🎬-☆
    
    Lily wakes up in her bedroom in the middle of the night. She heard a loud BAN outside the house.
    Now she has two choices she can either stay in the room or check what the sound might be about.
    
    Type your choice: Stay or Evaluate?
""")

Good going! Now we have the scene set and it turns out to be interesting as well and look here comes you first choice! Let’s now take the input from user and enter the conditional statements for each choice made.

We need to make sure that our game has answers to all types of inputs made by the user and it doesn’t result in an error in any choice made.

def scene1():
    import time
    print("""WELCOME TO THE ADVENTURE GAME!
        Let's start the action! ☆-🎬-☆

        Lily wakes up in her bedroom in the middle of the night. She heard a loud BAN outside the house.
        Now she has two choices she can either stay in the room or check what the sound might be about.

        Type your choice: Stay or Evaluate?
    """)

    c1 = input()
    time.sleep(2)
    ans = 'incorrect'
    while(ans=='incorrect'):
        if(c1.upper()=="STAY"):
            print("nLily decides to stay in the room and ends up staying inside forever as noone seems to come to help her.")
            ans = 'correct'
        elif(c1.upper()=="EVALUATE"):
            print("Lily exits the room silently and reaches the main hall.")
            ans='correct'
            scene2()
        else:
            print("ENTER THE CORRECT CHOICE! Stay or Evaluate?")
            c1 = input()

We take the first choice input and then we will create a variable that will confirm if our answer is correct or incorrect. Then we create the conditional loop and if-else statements. The game keeps on asking for the choice again and again until the answer given is valid.

Now the first scene is complete, we can move on to the next scene and build the whole game in the same way. Below we have the code for the second scene.

def scene2():
    import time
    print("""
            In the main hall, she finds a strange but cute teddy bear on the floor. 
            She wanted to pick the teddy up. 
            But should she? It doesn't belong to her. (•˳̂•̆)

            Type your choice: Pick or Ignore?

            """)
    time.sleep(2)
    c1 = input()
    ans = 'incorrect'
    while(ans=='incorrect'):
        if(c1.upper()=="PICK"):
            print("""nThe moment Lily picked up the the teddy bear. The Teddy bear starts TALKING!The bear tells Lily that she is in grave danger as there is a monster in the house.And the monster has captured her PARENTS as well!But he hugged her and told her not to get scared as he knows how to beat the moster!""")
            time.sleep(2)
            print("""nThe bear handed lily a magical potion which can weaken the moster and make him run away!He handed her the potion and then DISAPPEARED!Lily moved forward.""")
            ans = 'correct'
            pick="True"
        elif(c1.upper()=='IGNORE'):
            print("""nLily decided not to pick up the bear and walked forward.""")
            ans='correct'
            pick="False"
        else:
            print("Wrong Input! Enter pick or ignore?")
            c1=input()
    time.sleep(2)
    scene3(pick)

The code for the third scene is as follows. Now the result of the third scene depends on the choice made in scene2 which is if the teddy bear was picked or ignored and if the main protagonist received the potion or not.

def scene3(pick_value):
    import time
    print("""nnAfter walking for a while, Lily saw the MONSTOR in front of her!
    It had red eyes and evil looks. She got very scared! """)
    time.sleep(2)
    if(pick_value=="True"):
        time.sleep(2)
        print("""But then she remembered! She had the magic portion and she threw it on the moster!
              Well she had nothing to lose!""")
        time.sleep(2)
        print("n The monster SCREAMED in pain but he managed to make a portal and pushed Lily to a new world!")
    elif(pick_value=="False"):
        print("The monster attacked Lily and hurt her! She was then thrown to the new world by the monster!")

We will be ending chapter 1 of the story after three scenes. You can expand or even change the whole story according to your preference.

To start the story simply start the scene1 of the story.

scene1()
print("nn")
print("=================================END OF CHAPTER 1=================================")

The result of the story above is shown below. And it is pretty great!

text-based adventure game
Text Based Adventure Game Output

Conclusion

Now you know how to build simple and easy text-based adventure games all by yourself! You can try out your own unique story as well! Happy coding! Thank you for reading!


 

·

8 min read
· Updated
aug 2022

· General Python Tutorials

In this tutorial, we will make a simple text adventure game with Python and some of its modules like os, json, and pyinputplus.

We will focus on the code and make a system that allows prompts that lead to many other prompts. We also make an inventory system.

Let us go over how the text adventure story will be stored. Below you see a template of one prompt:

"0": ["Text", [possiblities], "My Text", "action"],

Each prompt will be an item in a dictionary that contains a list of four items. We use a dictionary because there can’t be any duplicate keys. The first item of the list will be the text of the prompt itself, and the second one is another list that holds the indexes/keys of the prompts this one can lead to.

The third item is the text of this prompt when used on other prompts. When we program the system, we will see what this means, and last but not least, we have the action of this prompt. This will tell the program whether to add or subtract a kind of item.

Below is our (really pointless) story. As you see, the first prompt leads to prompts one and two, and so on.

{
    "0": ["You embark on a new adventure, you are at a conjunction where do you go?", [1, 2], "Go Back", ""],
    "1": ["You Encounter an angry Mob of Programmers, what do you do?", [3, 4], "Go Right", ""],
    "2": ["You see the City of schaffhausen in front of you", [0, 3], "Go Left", ""],
    "3": ["I dont know why you did that but okay.", [4, 5], "Use Banana", "minus-clock"],
    "4": ["Seems like it worked they did not notice you. One of them slips you a banana", [4, 5], "Pull out Laptop", "plus-banana"],
    "5": ["The Banana was poisonous", ["end"], "Eat Banana", ""],
    "10": ["You fell over and now you are in grave pain ... ", ["end"], "Pull out Laptop", ""]
}

The whole story is saved in a JSON file named story.json. Let us start coding.

Imports

We start with the imports. We get the os module to clear the console before every prompt, so the console is cleaner. We also get json to parse the .json file to a valid Python dictionary. Lastly, we get the pyinputplus module to use the inputChoice() function, giving the user a limited number of correct items to choose from. Remember that we have to install it with:

$ pip install PyInputPlus
# Import pyinputplus for choice inputs and os to clear the console.
import pyinputplus
import os
import json

Setting up some variables

Let’s continue setting up some variables and opening the .json file. The currentKey variable will hold the key of the current prompt and currentKeys will have all possible following keys/prompts of the current prompt.

The itemAlreadyAdded variable will just be used to tell whether we have already been here or not in the last prompt. This will be used when we want to display the inventory.

# setting up some variables
currentKey = '0'
currentKeys = []
itemAlreadyAdded = False

After that, we will open the JSON file with a context manager and parse the file with json.load(). We store the parsed dictionary in the storyPrompts variable.

# Get the Story Prompts
# A dictionary is used because we dont want to allow
# duplicate keys
with open('story.json', 'r') as f:
    storyPrompts = json.load(f)

You can check this tutorial to learn more about JSON files in Python.

In the end, we also define a dictionary that holds the inventory.

inventory = {
    'banana(s)': 0,
    'clock(s)': 2,
    'swords(s)': 0,
}

StoryPrompts Check

We will now briefly transform the story dictionary to work with our program. To do this, we loop over it and get the prompt text and the leading keys. *_ is used to omit the other values that are to be unpacked.

# Check if the prompts are valid
for prompt in storyPrompts:
    promptText, keys, *_ = storyPrompts[prompt]

We first will check if the prompt text ends with a ':'. If that is not the case, we add it and set the value in the dictionary.

    # Add ":" at the end of the prompt Text
    if not promptText.endswith(':'):
        storyPrompts[prompt][0] = promptText + ': '

After that, we also transform all the numbers in the leading keys list into strings because we can only access a dictionary with strings, not integers.

    # Check if the keys are strings, if not transform them
    storyPrompts[prompt][1] = [str(i) for i in keys]

Prompts Loop

Before making the prompt loop, we give the user instructions, telling him that he can view the inventory with the -i command.

# Giving the user some instructions.
print('Type in the number of the prompt or -i to view your inventory ... have fun.')

Now let us get into the prompt loop. This is an infinite while loop that we will stop from within.

# Prompt Loop
while True:

In the loop, we start by clearing the console with the os.system() function.

    # Clearing the Console on all platforms
    os.system('cls' if os.name == 'nt' else 'clear')

After that, we get all the data from the current prompt except its text in other prompts and save them to variables.

    # Get the current prompt all its associated data
    currentPrompt, currentKeys, _, action = storyPrompts[currentKey]

Now, if the string 'end' is in the currentKeys list, we know that this prompt is the end so that we will exit the while loop:

    # Finish the Adventure when the next keys list contains the string 'end'
    if 'end' in currentKeys:
        break

But in most cases, the loop will continue with the loop, so we know to check if the action says something special. Remember, the action is the last item on the list. If minus or plus is in the action, we know that the action will add or subtract to the items dictionary. Currently, we only do all this if itemAlreadyAdded is False:

    # Look for inventory Changes
    if not itemAlreadyAdded:
        if 'minus' in action:
            inventory[action.split('-')[1]+'(s)'] -= 1
        if 'plus' in action:
            inventory[action.split('-')[1]+'(s)'] += 1

Next, we loop over all of the currentKeys to add them to the prompt text, so the user knows their options.

    # Add Option Descriptions to the current Prompt with their number
    for o in currentKeys:

Now the tedious thing about this is that we have to check if the prompt this option leads to subtracting an item that the user did not have. In the code block below, we do just that. We first define a variable and get the action from the option prompt. Then we check if the string minus is in the action. If that is the case, we get the item from the action, which will be after a '-'; that is why we split it by that.

Last but not least, we check if this item is zero, which means this route is not available because it will subtract an item that the user has none of. Then we set invalidOption to True:

        invalidOption = False
        thisaction = storyPrompts[o][3]
        if 'minus' in thisaction:
            item = storyPrompts[o][3].split('-')[1]+'(s)'
            if inventory[item] == 0:
                print(storyPrompts[o][3].split('-')[1]+'(s)')
                invalidOption = True

So if the option is valid, we add it to the prompt text with the number the user has to type in to get there.

        if not invalidOption:
            currentPrompt += f'n{o}. {storyPrompts[o][2]}'

After adding all the valid options, we also add a string telling the user what do you do?

currentPrompt += 'nnWhat do you do? '

Now we can finally ask the user what they do. To do this, we use the pyinputplus.inputChoice() function, which has a choices parameter that we can supply with a list of strings representing the options the input will allow. That is why give it the currentKeys plus the string -i, which the user can use to display the inventory. The prompt argument is our prompt which we build earlier.

We save this input in the userInput variable.

    # Get the input from the user, only give them the keys as a choice so they dont
    # type in something invalid.
    userInput = pyinputplus.inputChoice(choices=(currentKeys + ['-i']), prompt=currentPrompt)

Now if -i is in the user input, we know the user wants to see their inventory:

    # Printing out the inventory if the user types in -i
    if '-i' in userInput:
        print(f'nCurrent Inventory: ')
        for i in inventory:
            print(f'{i} : {inventory[i]}')
        print('n')
        input('Press Enter to continue ... ')

We also set the itemAlreadyAdded variable to True, which is just done to ensure that we don’t add or subtract an item again later. If the user did not type in -i. we set this same variable to False. In the end, we also set the currentKey to the userInput.

        itemAlreadyAdded = True
        continue
    else:
        itemAlreadyAdded = False
    currentKey = userInput

After the loop

After the prompt loop, we print out the text of the last prompt.

# Printing out the last prompt so the user knows what happened to him.
print(storyPrompts[currentKey][0])
print('nStory Finished ...')

Show Case

Now let’s see the text adventure in action:

showcase

Conclusion

Excellent! You have successfully created a text adventure game using Python code! See how you can add more features to this program, such as more checks for the story prompts or more action types. You can also edit the story.json to make a completely different story without changing the code!

Learn also: How to Make a Simple Math Quiz Game in Python.

Happy coding ♥

View Full Code

Read Also

How to Make a Calculator with Tkinter in Python

How to Make a Text Editor using Tkinter in Python

How to Make a Simple Math Quiz Game in Python

Comment panel

Practice your Python programming with some simple text processing and decision handling to create a playable game.

Person holding gameboy console

A text adventure game is a fun project you can undertake if you are learning how to program. You can make a text adventure game using Python, run it in a command line, and change the story based on the text that the player enters.

The Python script will cover several kinds of fundamental programming concepts. This includes print statements, if statements, and functions.

How to Create the Python Script and Add Story Content

You can create a script using a standard text file with a .py extension. If you are not familiar with Python syntax, take a look at some basic Python examples that may help you learn it faster. You can also look at other useful Python one-liners to perform certain tasks.

In the main function of the Python file, set up your story and welcome message.

  1. Create a new file called «AdventureGame.py».
  2. In the file, add the main starting function. The function will include a brief opening story to welcome the player to the adventure game. It will then call another function called introScene().
     if __name__ == "__main__":
      while True:
        print("Welcome to the Adventure Game!")
        print("As an avid traveler, you have decided to visit the Catacombs of Paris.")
        print("However, during your exploration, you find yourself lost.")
        print("You can choose to walk in multiple directions to find a way out.")
        print("Let's start with your name: ")
        name = input()
        print("Good luck, " +name+ ".")
        introScene()

How to Create Multiple Scenes and Options in the Story

Your story will contain several scenes or «rooms». You can create a function for each scene so that you can re-use it later if the player ends up entering the same room again.

Each scene will also have different choices of where to go. It is a good idea to map out your story before coding the scenarios, to make sure your story is well organized.

Map of storyline in Python game

Each scene will have a list of valid directions, and an if-statement for the multiple paths the player can take. Depending on the path the player takes, the program will call the next scene.

Create functions for the scenes that will occur in the story.

  1. Create the introScene() function above the main function. Add a message and the directions that the player can walk in.
     def introScene():
      directions = ["left","right","forward"]
      print("You are at a crossroads, and you can choose to go down any of the four hallways. Where would you like to go?")
      userInput = ""
      while userInput not in directions:
        print("Options: left/right/backward/forward")
        userInput = input()
        if userInput == "left":
          showShadowFigure()
        elif userInput == "right":
          showSkeletons()
        elif userInput == "forward":
          hauntedRoom()
        elif userInput == "backward":
          print("You find that this door opens into a wall.")
        else:
          print("Please enter a valid option.")
  2. Depending on the user’s input, the program will call another scene. For example, if the player types «left», the program will display the scene showShadowFigure() to the player. From this room, if the player goes backward, the game will take them back to the intro scene. If they go left or right, they will either enter another room or hit a dead end.
     def showShadowFigure():
      directions = ["right","backward"]
      print("You see a dark shadowy figure appear in the distance. You are creeped out. Where would you like to go?")
      userInput = ""
      while userInput not in directions:
        print("Options: right/left/backward")
        userInput = input()
        if userInput == "right":
          cameraScene()
        elif userInput == "left":
          print("You find that this door opens into a wall.")
        elif userInput == "backward":
          introScene()
        else:
          print("Please enter a valid option.")
  3. Add the camera scene for if they turn right. This is where the player can find one of the exits. Call the quit() function to end the game. The player can also still choose to move backward to the previous scene.
     def cameraScene():
      directions = ["forward","backward"]
      print("You see a camera that has been dropped on the ground. Someone has been here recently. Where would you like to go?")
      userInput = ""
      while userInput not in directions:
        print("Options: forward/backward")
        userInput = input()
        if userInput == "forward":
          print("You made it! You've found an exit.")
          quit()
        elif userInput == "backward":
          showShadowFigure()
        else:
          print("Please enter a valid option.")
  4. Back to the beginning of the adventure game, you will still need to add the functions for the remaining scenes. Add the hauntedRoom() scene for if the player chooses to move forward. This will also end the game depending on the player’s choice.
     def hauntedRoom():
      directions = ["right","left","backward"]
      print("You hear strange voices. You think you have awoken some of the dead. Where would you like to go?")
      userInput = ""
      while userInput not in directions:
        print("Options: right/left/backward")
        userInput = input()
        if userInput == "right":
          print("Multiple goul-like creatures start emerging as you enter the room. You are killed.")
          quit()
        elif userInput == "left":
          print("You made it! You've found an exit.")
          quit()
        elif userInput == "backward":
          introScene()
        else:
          print("Please enter a valid option.")
  5. You can also add more interesting content to the game. Create a global variable, at the very top of the file, called «weapon». It will either be true or false depending on if the player finds it.
     weapon = False 
  6. In one of the rooms, set the weapon variable to true if the player finds it. The player can use it in the next room if needed.
     def showSkeletons():
      directions = ["backward","forward"]
      global weapon
      print("You see a wall of skeletons as you walk into the room. Someone is watching you. Where would you like to go?")
      userInput = ""
      while userInput not in directions:
        print("Options: left/backward/forward")
        userInput = input()
        if userInput == "left":
          print("You find that this door opens into a wall. You open some of the drywall to discover a knife.")
          weapon = True
        elif userInput == "backward":
          introScene()
        elif userInput == "forward":
          strangeCreature()
        else:
          print("Please enter a valid option.")
  7. If the player finds the weapon, they can kill the enemy in the next room, and find another exit. Otherwise, the enemy will kill them.
     def strangeCreature():
      actions = ["fight","flee"]
      global weapon
      print("A strange goul-like creature has appeared. You can either run or fight it. What would you like to do?")
      userInput = ""
      while userInput not in actions:
        print("Options: flee/fight")
        userInput = input()
        if userInput == "fight":
          if weapon:
            print("You kill the goul with the knife you found earlier. After moving forward, you find one of the exits. Congrats!")
          else:
            print("The goul-like creature has killed you.")
          quit()
        elif userInput == "flee":
          showSkeletons()
        else:
          print("Please enter a valid option.")

How to Run the Python Script

You can run the script using a terminal or command prompt. As you enter input into the terminal, the story will continue to move forward to the next scene.

  1. Using a terminal or command prompt, navigate to the location where you stored the file.
     cd C:UsersSharlDesktopPython 
  2. Run the script.
     python AdventureGame.py 
  3. The opening message will welcome you to start playing the game.
    Python Adventure Game in command line
  4. Type from the available options listed, such as «left», «right», or «backward». If you enter an invalid input, the game will prompt you for a valid one.
    Python Adventure Game in command line
  5. You can also replay the game to choose another path.
    Adventure Game in command prompt

You can download the full source code for the project from this GitHub repository.

Create a Simple Game Using Just One Python Script

You can create a text adventure game using a Python script, and run it in a terminal or command line. Inside the Python file, you can present the player with a welcoming message and initial story. The player can then type in their actions based on the options you present.

If you want to become a more well-rounded Python developer, you can have a look at some of the useful tools that you can use or integrate with Python.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
a = 0
b = 0
c = 0
d = 0
e = 0
print(' вы стоите на развилке, перед вами три двери, в какую пойдете: 1(каменная дверь), 2(старая обшарпанная дверь) или 3(обычная деревянная межкомнатная дверь)? (ответ цифрой)')
a = input()
if a == '1':
    print(' вы выбрали каменную дверь, но за ней вас ждали еще 2 двери, в какую пойдете: 1 или 2? (ответ цифрой)')
    b = input()
    if b == '1':
        print('вы не увидели ничего ,кроме кромешной тьмы, но не мешкая ни секунды ступили туда, правда там был обрыв и пролетев более десятка метров вы успешно распластались на полу усеянного сталагмитами, вы, конечно не выжили')
    else:
        print('за этой дверью вы почуствовали слабый ветер, похоже там выход! Вы пробежали вглубь тоннеля и увидели свет! Пройдя еще немного вы поняли что это выход... правда пройдя еще чуть-чуть вы поняли что диаметром этот выход около 10 см и вы вряд ли туда пролезите, что ж, можно вернуться и попробовать найти другой выход, хотя нет, дверь закрылась и вряд ли вы ее теперь откроете, прийдется вам остаться здесь до конца своих дней, хотя попробуйте покричать в это отверстие, вдруг вас услышат, вы умерли от голода')
elif a == '2':
    print('вы выбрали обшарпанную старую дверь, за которой был какой-то непонятный каменный зал с каменными плитами на полу, всего 3 ряда по 3 плиты, нужно выбрать правильный путь, куда же вы наступите? какой то здесь потолок слишком неестественный (1 ,2 или 3 плиту)')
    c = input()
    if c == '1':
        print('увы плита провалилась и вы упали в пропасть')
    elif c == '2':
        print('вроде все впорядке, куда дальше?(1 ,2 ,3)')
        d = input()
        if d == '1':
            print('пока все хорошо, куда дальше?(1 ,2 ,3)')
            e = input()
            if e == '1':
                print('ура, вы прошли и с вами ничего не случилось! а вот лестница, поднявшись по которой вы видите что тут еще и дверь, открыв которую вы понимаете ,что это выход! а еще вы понимаете ,что не надо было наступать на цифру 1 два раза так как у вас в ноге ядовитый дротик и вы, на самом деле лежите на плите не в силах двинуться и быстро умираете')
            elif e == '2':
                print('пожалуй, это было правильное решение, ведь ничего не произошло и вы наконец выбрались! плиты и двери позади, а теперь вы скоро выйдете отсюда... или нет? видимо здесь нету двери, ведущей наружу, а вот же кнопка! вы нажимаете и слышите щелчок и звук движения камней. вы ждете пока откроется потайной люк или дверь но ничего не происходит, обернувшись вы видите как потолок начинает обваливаться, вот что было с потолком, вы, кстати были раздавлены')
            elif e == '3':
                print('вы решили что если цифра 2 и 1 были то теперь должна быть тройка, но топор, отсекший вам голову это опроверг')
            else :
                print('вы сделали неправильный выбор, мы уже выехали за вами')
        elif d == '2':
            print('не стоило два раза подряд выбирать одно и то же число, то же вам сказали шипы, выскочившие из пола, только на своем языке, на языке боли')
        elif d == '3':
            print('это мог бы быть правильный ответ но это не так, ведь, пол под вами провалился и вы попали в комнату с голодным львом, никто не знает как он тут оказался и как он еще жив но увы вы были съедены им')
        else:
            print('вы сделали неправильный выбор, мы уже выехали за вами')
    elif c == '3':
        print('вы решили наступить на плиту с номером 3 в 1 ряду но увы это был не правильный выбор, вы бы и не поверили, но это вам уже доказал десяток стрел, внезапно вылетевший откуда-то и отправивший вас в другой мир')
    else:
        print('вы сделали неправильный выбор, мы уже выехали за вами')
elif a == '3':
    print('вы решили зайти в обычную деревянную межкомнатную дверь, за ней вы увидели комнату , напоминающую обычную комнату в доме, а пройдя дальше вы увидели человека, пишущего программу к этому квесту, который дописывал эту строчку, так что вы не стали ему мешать и просто вышли из дома и пошли своей дорогой, конец')

Text-Based Adventure Game Using Python

What is the definition of a Text-Based Game?

A text-based game is a basic input-output game that is entirely text-based. Users have alternatives to address different scenarios in this sort of game since they come with choices made by the user in the form of inputs.

Python implementation of a Text-Based Adventure Game

Let’s begin by printing the first scene and then seeing how the tale progresses. Simply use the print function to do this. We can also add emoticons and emojis to make it more entertaining!

print("""WELCOME TO THE ADVENTURE GAME!
    Let's start the action! ?-????-?
     
    Lily wakes up in her bedroom in the middle of the night. She heard a loud BAN outside the house.
    Now she has two choices she can either stay in the room or check what the sound might be about.
     
    Type your choice: Stay or Evaluate?
""")

You’re doing well! Now that we’ve created the scenario, it turns out to be rather exciting, and here comes your first decision! Now we’ll take the user’s input and create conditional statements for each option selected.

We must ensure that our game provides responses to all forms of user inputs and that no option made by the user results in an error.

def scene1():
    import time
    print("""WELCOME TO THE ADVENTURE GAME!
        Let's start the action! ?-????-?
 
        Lily wakes up in her bedroom in the middle of the night. She heard a loud BAN outside the house.
        Now she has two choices she can either stay in the room or check what the sound might be about.
 
        Type your choice: Stay or Evaluate?
    """)
 
    c1 = input()
    time.sleep(2)
    ans = 'incorrect'
    while(ans=='incorrect'):
        if(c1.upper()=="STAY"):
            print("nLily decides to stay in the room and ends up staying inside forever as noone seems to come to help her.")
            ans = 'correct'
        elif(c1.upper()=="EVALUATE"):
            print("Lily exits the room silently and reaches the main hall.")
            ans='correct'
            scene2()
        else:
            print("ENTER THE CORRECT CHOICE! Stay or Evaluate?")
            c1 = input()

We’ll start with the first option and then add a variable to validate if our response is accurate or erroneous. The conditional loop and if-else statements are then created. The game will keep asking you for your option until you offer a good response.

Now that the first scene is finished, we can go on to the next scene and continue building the game in this manner. The code for the second scenario may be seen below.

def scene2():
    import time
    print("""
            In the main hall, she finds a strange but cute teddy bear on the floor. 
            She wanted to pick the teddy up. 
            But should she? It doesn't belong to her. (•??•?)
 
            Type your choice: Pick or Ignore?
 
            """)
    time.sleep(2)
    c1 = input()
    ans = 'incorrect'
    while(ans=='incorrect'):
        if(c1.upper()=="PICK"):
            print("""nThe moment Lily picked up the the teddy bear. The Teddy bear starts TALKING!The bear tells Lily that she is in grave danger as there is a monster in the house.And the monster has captured her PARENTS as well!But he hugged her and told her not to get scared as he knows how to beat the moster!""")
            time.sleep(2)
            print("""nThe bear handed lily a magical potion which can weaken the moster and make him run away!He handed her the potion and then DISAPPEARED!Lily moved forward.""")
            ans = 'correct'
            pick="True"
        elif(c1.upper()=='IGNORE'):
            print("""nLily decided not to pick up the bear and walked forward.""")
            ans='correct'
            pick="False"
        else:
            print("Wrong Input! Enter pick or ignore?")
            c1=input()
    time.sleep(2)
    scene3(pick)

The following is the code for the third scene. The outcome of the third scene is now determined by the decision made in scene 2, namely whether the teddy bear was chosen or ignored, and whether the main protagonist got the potion or not.

After three scenes, we’ll wrap up Chapter 1 of the tale. Depending on your preferences, you may extend or even modify the whole tale.

Simply begin the first scene of the tale to begin the story.

scene1()
print("nn")
print("=================================END OF CHAPTER 1=================================")

The outcome of the preceding narrative is shown below. And it’s a lot of fun!

Adventure

Conclusion

You now know how to create basic text-based adventure games on your own! You may even try out your own original narrative! Have fun coding! Thank you for taking the time to read this!

Text-Based Adventure Game Using Python

What is the definition of a Text-Based Game?

A text-based game is a basic input-output game that is entirely text-based. Users have alternatives to address different scenarios in this sort of game since they come with choices made by the user in the form of inputs.

Python implementation of a Text-Based Adventure Game

Let’s begin by printing the first scene and then seeing how the tale progresses. Simply use the print function to do this. We can also add emoticons and emojis to make it more entertaining!

print("""WELCOME TO THE ADVENTURE GAME!
    Let's start the action! ?-????-?
     
    Lily wakes up in her bedroom in the middle of the night. She heard a loud BAN outside the house.
    Now she has two choices she can either stay in the room or check what the sound might be about.
     
    Type your choice: Stay or Evaluate?
""")

You’re doing well! Now that we’ve created the scenario, it turns out to be rather exciting, and here comes your first decision! Now we’ll take the user’s input and create conditional statements for each option selected.

We must ensure that our game provides responses to all forms of user inputs and that no option made by the user results in an error.

def scene1():
    import time
    print("""WELCOME TO THE ADVENTURE GAME!
        Let's start the action! ?-????-?
 
        Lily wakes up in her bedroom in the middle of the night. She heard a loud BAN outside the house.
        Now she has two choices she can either stay in the room or check what the sound might be about.
 
        Type your choice: Stay or Evaluate?
    """)
 
    c1 = input()
    time.sleep(2)
    ans = 'incorrect'
    while(ans=='incorrect'):
        if(c1.upper()=="STAY"):
            print("nLily decides to stay in the room and ends up staying inside forever as noone seems to come to help her.")
            ans = 'correct'
        elif(c1.upper()=="EVALUATE"):
            print("Lily exits the room silently and reaches the main hall.")
            ans='correct'
            scene2()
        else:
            print("ENTER THE CORRECT CHOICE! Stay or Evaluate?")
            c1 = input()

We’ll start with the first option and then add a variable to validate if our response is accurate or erroneous. The conditional loop and if-else statements are then created. The game will keep asking you for your option until you offer a good response.

Now that the first scene is finished, we can go on to the next scene and continue building the game in this manner. The code for the second scenario may be seen below.

def scene2():
    import time
    print("""
            In the main hall, she finds a strange but cute teddy bear on the floor. 
            She wanted to pick the teddy up. 
            But should she? It doesn't belong to her. (•??•?)
 
            Type your choice: Pick or Ignore?
 
            """)
    time.sleep(2)
    c1 = input()
    ans = 'incorrect'
    while(ans=='incorrect'):
        if(c1.upper()=="PICK"):
            print("""nThe moment Lily picked up the the teddy bear. The Teddy bear starts TALKING!The bear tells Lily that she is in grave danger as there is a monster in the house.And the monster has captured her PARENTS as well!But he hugged her and told her not to get scared as he knows how to beat the moster!""")
            time.sleep(2)
            print("""nThe bear handed lily a magical potion which can weaken the moster and make him run away!He handed her the potion and then DISAPPEARED!Lily moved forward.""")
            ans = 'correct'
            pick="True"
        elif(c1.upper()=='IGNORE'):
            print("""nLily decided not to pick up the bear and walked forward.""")
            ans='correct'
            pick="False"
        else:
            print("Wrong Input! Enter pick or ignore?")
            c1=input()
    time.sleep(2)
    scene3(pick)

The following is the code for the third scene. The outcome of the third scene is now determined by the decision made in scene 2, namely whether the teddy bear was chosen or ignored, and whether the main protagonist got the potion or not.

After three scenes, we’ll wrap up Chapter 1 of the tale. Depending on your preferences, you may extend or even modify the whole tale.

Simply begin the first scene of the tale to begin the story.

scene1()
print("nn")
print("=================================END OF CHAPTER 1=================================")

The outcome of the preceding narrative is shown below. And it’s a lot of fun!

Adventure

Conclusion

You now know how to create basic text-based adventure games on your own! You may even try out your own original narrative! Have fun coding! Thank you for taking the time to read this!

Понравилась статья? Поделить с друзьями:
  • Как написать терминологический диктант
  • Как написать текст чтобы товар купили
  • Как написать терапевтическую сказку для ребенка
  • Как написать терапевтическое письмо
  • Как написать текст чтобы привлечь клиентов