Creating A Text Based Adventure Game
PYer (3653)

Creating A Text Based Adventure Game

This is based on a game I created ( Aliens Adventure Game ).

Knowledge Required

Before starting this tutorial, make sure you have a basic understanding of the following.

  • Basic classes
  • Basic inheritance
  • Input and Printing (Obviously)
  • Dictionaries
  • While loops

Introduction

This game's code is mainly based on classes. Each room is a simple class, with a play function that plays that room. Each play function returns a string, such as "corridor" or "bomb hold". The rooms will all be stored in a dict titled engine, and with each room held and accesed from there.

Creating The Game

Now it is time to actually create the game. The file for the code, if you want to copy and paste it or play around with it can be found at @Pyer Aliens Adventure Game Repl
Create a python repl and open main.py

Creating the Room class

In the file main.py type in this:

class Room():
  def __init__(self): pass
  def play(self):
    print('This room hasnt been created yet.')

There we go. If you meet the knowledge requirments of above, you should understand this. Basically a class called Room() is being created, and does nothing when it is created (initialized). The play function does nothing yet.

Creating rooms

In the file main.py again create a room
This example here is from my aliens adventure game:

from replit import clear as c
import sys

# Code before here

class Intro(Room):
  def play(self):
    c()
    print('Welcome To Aliens Adventure Game!\nObjective: \n\tFind the bomb to be planted on Earth, \n\tPlace it on the bridge, and escape\n\tbefore the spaceship blows up.')
    if not input('Ready? [y/n]: ') == 'y': sys.exit()
    c()
    print('You are onboard an alien spaceship. You have managed to reach the main room, without spotting any aliens. Hopefully, this streak of good luck continues until you escape the ship. But as any good space invader knows, that is never the case. You look around the room deciding what to do when an alien pops out of a corridor. You put a hand on your blaster.\nYour options are:\n\t1. Shoot\n\t2. Tell A Joke\n\t3. Run')
    o = input('Move? [1, 2, 3]: ')
    c()
    if o == '1':
      print('You pull out your blaster and shoot the alien. Apparently the alien has enabled a force field as the bullet rebounds off of him. He is angered at your threating gesture,pulls out his own blaster, and shoots you in the head. You have determined the fate of thousands of inoccent people on earth.')
      return 'game over'
    elif o == '2':
      print('You remeber your old school training on the alien language. You say the first joke that pops in your mind:\n\tAyay anmay andyay ishay orsehay alkedway \n\tintoyay ayay arbay. Ouyay ouldway \n\tavehay oughtthay eythay ouldway avehay \n\tuckedday.\nThe alien doubles over laughing and you quickly rush past him and through the door into the corridor.')
      return 'corridor'
    elif o == '3':
      print('You quickly scan your surroundings, for an exit. You turn around and attempt to exit the way you came in, but the aline quickly pulss out his blaster and shoots your moving shape.  You have determined the fate of thousands of inoccent people on earth.')
      return 'game over'

There we go! Continue creating rooms. The basic template is like this:

class AnotherRoom(Room):
    def play():
        # Text
        return 'next room'
Creating the engine

This is based on a while True loop.
First, define a dict called engine.
In my game this looks like:

engine = {
  'game over': Game_Over(),
  'intro': Intro(),
  'corridor': Corridor(),
  'bomb hold': Bomb_Hold(),
  'bridge': Bridge(),
  'escape room': EscapeRoom(),
  'win': Win()
}

The basic template is this:

engine = {'mainroom': AnotherRoom() }

Now we have to define the first room like this:

room = engine['intro'].play()

Then add this while True:

while True:
  room = engine[room]
  room = room.play()

There we go!
Now you can add other rooms. A recommendation would be to add a Win() and Lose() class, so that the user goes to those rooms when they die or win.
Here is an example repl. https://repl.it/@PYer/Aliens-Adventure-Game

You are viewing a single comment. View All
ZeeMan (8)

Here is my incomplete game:

#author:kegaming860
#time: Friday, June 26 2020 at 2:02 pm
#description: My very first game and a simple text-based game.
#HOW TO USE: Install any reputable python interpreter (I use PyCharm CE), copy #this code, and run it.
#Alternatively, on MacOS and Linux distributions, open a terminal window by clicking the icon or

pressing control-alt-T and type the following command: python3 <name of your game>.

#If it says python3.7 is not installed, type (assuming you are root user,
#if you are not, then ask whoever is to sign in): sudo apt install python, enter the password, and it should install.
#CREDITS TO THE CREATOR OF https://www.youtube.com/watch?v=miuHrP2O7Jw.
#I will make a more advanced version of this game that implement things like uuids and BTrees.

import random
import sys
import time

mangonum = random.randint(2, 5)
Q = input("This is a text based adventure game. Do you want to play? " +
"y for yes, anything else for no. ")
if Q == "y":
print("Yay! Let's proceed.")
print("Loading...")
time.sleep(1)
print("Locating References... 25%")
time.sleep(2)
print("Unpacking Libraries... 50%")
time.sleep(2)
print("Unzipping Archives... 75%")
time.sleep(2)
print("Reformatting Files... 100%")
time.sleep(1)
print("You are surrounded by green leaves and huge tree branches. " +
"It looks like a place you've never been to. How have you gotten here?")
else:
print ("Goodbye")
sys.exit()
W = input("Well oops. You figured out that you are lost in a jungle. You know you should get out " +
"of here. f to move forwards. ")
if W == "f":
print("You see a monkey on a mango tree.")
else:
print("You slowly notice a boa constrictor crushing your body. Your vision slowly fades away...")
sys.exit()
E = input("You realize you haven't eaten or had water. s to shake " +
"the tree and get some mangoes. ")
if E == "s":
print(str(mangonum) + " mangoes fell from the tree. You ate all of them.")
else:
print("You feel a sudden need for food and water. " +
"You reach for the mangoes, but you are weakened by dehydration and starvation. " +
"You slowly collapse and never get back up.")
sys.exit()
R = input("Suddenly, the monkey gets angry at you for stealing its food " +
"and starts attacking you. You " +
"know monkeys can rip humans apart. r to run for your life. ")
if R == "r":
print("Luckily, you escaped the monkey.")
else:
print("You feel a burst of pain as the monkey rips your limbs off.")
sys.exit()
T = input("You see a path that splits in 2 directions. You also see a " +
"sign. l to read the sign, w for west, and e for east. ")
if T == "l":
print("Warning: Please use animal-proof gear to go west.")
Y = input("You see a path that splits in 2 directions. " +
"w for west and e for east. ")
if Y == "w":
print("Sadly for you, you didn't heed the sign's warning and was eaten up by hungry lions.")
sys.exit()
if T == "w":
print("Sadly for you, you went into a lion's den. You were quickly " +
"devoured by the hungry beasts. Always read the sign!")
sys.exit()
if T == "e":
print("There is a chest. It probably has something in it.")
else:
print("A wild dog bites your leg off. You barely have time to scream.")
sys.exit()
U = input("You decide to see what is inside of it. It turns out there " +
"is a set of sturdy armor and a sword. You never expected to " +
"find treasure. e to equip yourself. ")
if U == "e":
print("You equip yourself. Now you think to yourself, 'I have " +
"everything but a shield. Maybe it's somewhere else.'")
else:
print("You were pummeled by a huge bear and you feel the bear dig in.")
sys.exit()
I = input("You walk ahead and see a huge dragon. Thankfully, you have the armor and a sword. " +
"h to hit the dragon. ")
if I == "h":
time.sleep(1)
print("Clang! The dragon's belly was sliced by the sword.")
else:
print("You became the dragon's fifth roast of the year.")
sys.exit()
O = input("Something shiny comes out. i to investigate.")
if O == "i":
print("It's the shield!.")
else:
print("Something comes from behind you, but you are quickly submerged " +
"into a huge vat of strange blueish acid, which dissolves you.")
sys.exit()
P = input("You come across a cave. e to enter.")
if P == "e":
print("You can see a sparkle in the distance, but then all the light goes out.")
else:
print("A colony of electric bats appear and shock you.")
sys.exit()
A = input("You decide to proceed. l to light a torch.")
if A == "l":
print("You can see a carving on the wall. It may be readable.")
else:
print("A poisonous spider crawls up your leg and bites you.")
sys.exit()
S = input("You walk to the carving. r to read.")
if S == "r":
print("It says, 'One way is a chest with treasure, and the other does not offer such pleasures.")
else:
print("You start breathing heavily as the air around you becomes stuffy. " +
"You were a victim of the toxic mold on the ceiling.")
sys.exit()
D = input("You push the carving lying on the wall to reveal a hidden entrance. " +
"It forks in 2 directions. An old bow sits nearby and you take it, along with the arrows. " +
"You notice that the arrows were pointing west. w for west and e for east.")
if D == "w":
print("The path west has multiple chests. Also, each chest has a rope attached to it. " +
"with a ball at the end. Maybe it’s a code?")
F = input("You inspect the balls closely. They have numbers on them. They says 1, 8, 5, 2, 3, 1. What is the code? " +
"a for 1, 1, 2, 3, 5, 8 and b for 1, 2, 1, 3, 5, 8.")
if F == "a":
print("You arrange the balls in that order. The chest in the middle flings open, revealing another person.")
time.sleep(1)
print("'Wake up', whispers your math teacher. It turns out you dozed off in math class. Thank you for playing!" +
"Goodbye!")
sys.exit()
if F == "b":
print("2 chests open. Each has something in it.")
J = input("Aaaaaaaaaaaaah! 6 monsters pop out. Each has big horns and huge teeth. h to hit. ")
if J == "h":
print("You killed the monsters. ")
else:
print("You scream as the monsters rip you apart and swallow you.")
sys.exit()
if D == "e":
print("A small, round, and fluffy creature walks up to you. Then, it starts following you around.")
else:
print("The carving rolls back into place, and you suffocate slowly.")
sys.exit()
G = input("Oddly enough, it wants you to pet it. p to pet the creature. ")
if G == "p":
print("It starts to lead you somewhere. Maybe it’s a way out?")
else:
print("The creature suddenly turns around and bites your face, causing fatal blood loss.")
sys.exit()
H = input("You think you should follow it. f to follow the creature. ")
if H == "f":
print("It turns out you were woken up by your barking dog. Thank you for playing! Goodbye!")
sys.exit()
else:
print("A heavy ball flattens you.")
sys.exit()