Text - Based Adventure Game - Caves

+2 Ethan Hann · November 10, 2014
This is the text based adventure game I'm currently working on. I haven't done a lot of commenting yet, but hopefully you guys can figure out what's going on in most of the code... I'm sure a lot of things can be refined but I just thought I would share it with ya'll. Enjoy!
(p.s. its 786 lines of code as of now)

#Caves - Text Based Adventure v.1
#Original release T.B.A.
#---work in progress---
import time
import random
import sys
import os
import pickle


class Player:
    def __init__(self, name, gold=20, health=100, inventory=[], state='normal', level=0):

        self.item_quantities = {'sword': 0, 'battle axe': 0, 'great sword': 0, 'great axe': 0, 'crossbow': 0,
                                'bow and arrow': 0, 'health potion': 0, 'strength potion': 0}
        self.item_strengths = {'sword': 10, 'battle axe': 20, 'great sword': 25, 'great axe': 35,
                               'crossbow': 60, 'bow and arrow': 80}
        self.selected_item = None
        self.name = name
        self.gold = gold
        self.health = health
        self.inventory = inventory
        self.state = state
        self.level = level


class Monster:
    def __init__(self, name, strength, health=100):
        self.name = name
        self.strength = strength
        self.health = health

commands = ('help', 'attack', 'flee', 'sleep', 'info', 'developer', 'yes', 'no', 'buy', 'get', 'exit', 'use', 'save',
            'select')

buy_commands = ('buy sword', 'buy battle axe', 'buy great sword', 'buy great axe', 'buy crossbow', 'buy bow and arrow')
buy_tup = ('sword', 'battle axe', 'great sword', 'great axe', 'crossbow', 'bow and arrow', 'health potion',
           'strength potion')
default_item_quantities = {'sword': 0, 'battle axe': 0, 'great sword': 0, 'great axe': 0, 'crossbow': 0,
                           'bow and arrow': 0, 'health potion': 0, 'strength potion': 0}

command = ""

monster_names = ['goblin', 'dwarf', 'zombie', 'ghoul']
level_1_monsters_strengths = [5, 10, 15]
level_2_monsters_strengths = [20, 25, 30]
level_3_monsters_strengths = [40, 45, 50]
level_4_monsters_strengths = [60, 70, 80]
boos_level_monsters_strengths = [90, 100, 120]

weapons = {'sword': 10, 'battle axe': 20, 'great sword': 25, 'great axe': 35, 'crossbow': 60, 'bow and arrow': 80}
weapons_list = [item for item in weapons.keys()]

potions = {'health potion': 'Random health boost', 'strength potion': 'Random strength boost'}
potions_list = [item for item in potions.keys()]

shop_prices = {'sword': 10, 'battle axe': 10, 'great sword': 20, 'great axe': 25, 'crossbow': 150, 'bow and arrow': 250,
               'health potion': 5, 'strength potion': 15}
shop_list = [item for item in shop_prices.keys()]


def sleep(player_obj):
    random_heal = random.randrange(15, 70)
    time1 = time.time()
    if player_obj.health >= 100:
        print("Can't sleep! Already at full health!")
        time.sleep(0.2)
    else:
        x = 0
        while x < random_heal:
            os.system('cls')
            print("Health: %s HP" % player_obj.health)
            if player_obj.health == 100:
                print("Healed %s HP" % x)
                time2 = time.time()
                elapsed_time = time2 - time1
                elapsed_time = int(elapsed_time) + 1
                print("Slept for %s hours. Gained %s health." % (elapsed_time, x))
                time.sleep(2)
                break
            else:
                player_obj.health += 1
                time.sleep(0.2)
                x += 1
        if player_obj.health == 100:
            pass
        else:
            print("Healed %s HP" % random_heal)
            time2 = time.time()
            elapsed_time = time2 - time1
            elapsed_time = int(elapsed_time) + 1
            print("Slept for %s hours. Gained %s health." % (elapsed_time, random_heal))
            time.sleep(2)
    save_object(player_obj, 'save.cave')


def save_object(obj, filename):
    with open(filename, 'wb') as output:
        pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)


def load(filename):
    with open(filename, 'rb') as inputs:
        game_data = pickle.load(inputs)
    return game_data


def continue_progress(player_obj):
    current_l = player_obj.level
    if current_l == 1:
        level1(player_obj)
    elif current_l == 2:
        level2(player_obj)
    elif current_l == 3:
        level3(player_obj)
    elif current_l == 4:
        level4(player_obj)
    elif current_l == 5:
        boss_level(player_obj)


def use(potion_name, player_obj):
    random_time = random.randint(5, 50)
    if potion_name == 'use health potion':
        if 'health potion' in player_obj.inventory:
            if player_obj.health >= 100:
                print("Cant use health potion! Already fully healed!")
            else:
                x = 0
                while x < random_time:
                    os.system('cls')
                    print("Health: %s HP" % player_obj.health)

                    if player_obj.health == 100:
                        print("Healed %s HP" % x)
                        break
                    else:
                        player_obj.health += 1
                        time.sleep(0.2)
                        x += 1
                if player_obj.health == 100:
                    pass
                else:
                    print("Healed %s HP" % random_time)
                player_obj.item_quantities['health potion'] -= 1
                if player_obj.item_quantities['health potion'] <= 0:
                    try:
                        player_obj.inventory.remove('health potion')
                        print("No more health potions!")

                    except ValueError:
                        print("No more health potions!")
                else:
                    pass

            save_object(player_obj, 'save.cave')
        else:
            print("You don't have any health potions.")

    elif potion_name == 'use strength potion':
        if 'strength potion' in player_obj.inventory:
            equipped_item = player_obj.selected_item
            player_obj.item_strengths[equipped_item] += random_time
            new_strength = player_obj.item_strengths[equipped_item]
            print("Added %s DP to %s" % (random_time, equipped_item.capitalize()))
            print("%s now has %s DP" % (equipped_item.capitalize(), new_strength))
            player_obj.item_quantities['strength potion'] -= 1
            if player_obj.item_quantities['strength potion'] <= 0:
                    player_obj.inventory.remove('strength potion')
                    print("No more strength potions!")
            save_object(player_obj, 'save.cave')
        else:
            print("You don't have any strength potions.")

    else:
        print("No such potion.")


def item_select(player_obj):
    info(player_obj)
    count = 0
    for item in player_obj.inventory:
        if item in weapons_list:
            count += 1
        elif item in potions_list:
            pass
    if count == 0:
        print("No weapons available for selection.")
        return False

    weapon = input("Weapon Selection: ")
    selecting = True
    while selecting:
        if weapon in player_obj.inventory:
            if weapon in potions_list:
                print("Can't use potions as weapons...")
                weapon = input("Weapon Selection: ")
            else:
                player_obj.selected_item = weapon
                selecting = False
        else:
            print("Weapon is not in inventory...")
            weapon = input("Weapon Selection: ")


def helps():
    print('''
    help : show help
    attack : attack monster
    flee : flee from attacking monster
    sleep : sleep and heal if not attacking
    info : show info about player
    developer : show info about game
    get : pick-up item in room (if exists)
    use <potion name> : 'use' a potion (can be used during battle)
    exit : exit the game (will ask if you would like to save)
    save : save the game (saves your inventory and other characteristics to a .cave file)
    ''')


def info(player_obj):
    name = player_obj.name.capitalize()
    banner("    %s    Inventory    " % name)
    print("Gold: %s" % player_obj.gold)
    print("Health: %s" % player_obj.health)
    print("")
    print("Weapons")
    print("---------------")
    for item in player_obj.inventory:
        if item in weapons_list:
            print('%s x' % str(player_obj.item_quantities[item]), item, ':', str(weapons[item]) + ' DP')
        else:
            continue
    print("")
    print("Potions")
    print("---------------")
    for item in player_obj.inventory:
        if item in potions_list:
            if item == 'health potion':
                print('%s x' % str(player_obj.item_quantities[item]), item, ': +%s HP' % str(potions[item]))
            elif item == 'strength potion':
                print('%s x' % str(player_obj.item_quantities[item]), item, ': +%s DP' % str(potions[item]))
        elif item not in weapons_list and item not in potions_list:
            print("None")
        else:
            continue
    print("")


def developer():
    banner("    Caves    ")
    print("Text Based Adventure Game")
    print("Lines of code: %s (as of now)" % 753)
    print("Created by Ethan D. Hann")
    print("")


def create_monster(level):
    if level == 1:
        monster = Monster(random.choice(monster_names), random.choice(level_1_monsters_strengths),
                          random.randint(50, 100))
        monster_tup = (monster.name, monster.strength, monster.health)
        return monster_tup
    elif level == 2:
        monster = Monster(random.choice(monster_names), random.choice(level_2_monsters_strengths),
                          random.randint(50, 100))
        monster_tup = (monster.name, monster.strength, monster.health)
        return monster_tup
    elif level == 3:
        monster = Monster(random.choice(monster_names), random.choice(level_3_monsters_strengths),
                          random.randint(50, 100))
        monster_tup = (monster.name, monster.strength, monster.health)
        return monster_tup
    elif level == 4:
        monster = Monster(random.choice(monster_names), random.choice(level_4_monsters_strengths),
                          random.randint(50, 100))
        monster_tup = (monster.name, monster.strength, monster.health)
        return monster_tup
    else:
        print("Invalid Level")


def shop(player_obj):
    global command
    banner("    Shop    ")
    print("")
    print("Weapons")
    print("---------------")
    print("Item Name : Price")
    print("")
    for item in weapons_list:
        print(item + " : " + str(shop_prices[item]))
    print("")
    print("Potions")
    print("---------------")
    print("Item Name : Price")
    print("")
    for item in potions_list:
        print(item + " : " + str(shop_prices[item]))
    print("")
    print('''Welcome to the shop. Take a moment to browse our inventory.
When your ready, type the item name to buy it.''')
    command = input("> ")
    buying = True
    while buying:
        inventory = player_obj.inventory
        if command == 'exit':
            save_object(player_obj, 'save.cave')
            break
        elif command == 'developer':
            developer()
            input("Press enter key to continue...")
            shop(player_obj)
        elif command == 'help':
            helps()
            input("Press enter key to continue...")
            shop(player_obj)
        elif command == 'info':
            info(player_obj)
            input("Press enter key to continue...")
            shop(player_obj)
        elif command in buy_tup:
            if player_obj.gold < shop_prices[command]:
                print("Not enough gold. Sorry; try another item or exit")
                print("You have %s Gold. Need: %s more" % (player_obj.gold, (shop_prices[command] - player_obj.gold)))
                command = input("> ")
            elif player_obj.gold >= shop_prices[command]:
                player_obj.gold -= shop_prices[command]
                save_object(player_obj, 'save.cave')
                print(player_obj.gold)
                if command in player_obj.inventory:
                    player_obj.item_quantities[command] += 1
                    print("Added one %s to inventory" % command)
                    save_object(player_obj, 'save.cave')
                else:
                    inventory.append(command)
                    player_obj.item_quantities[command] += 1
                    print("Added one %s to inventory" % command)
                    save_object(player_obj, 'save.cave')

                print("Coming right up!")
                print("You have %s Gold." % player_obj.gold)
                print("Anything Else? (type exit to exit the shop)")
                save_object(player_obj, 'save.cave')
                command = input("> ")
        else:
            print("Invalid command.")
            command = input("> ")


def tutorial():
    print("Tutorial")


def introduction():
    global command
    global answering
    global player
    global commands

    #Ask if a tutorial is wanted...
    print("Before playing, would you like a short tutorial on the basic commands?")
    command = input("> ")
    answering = True
    while answering:
        if command in commands and command == 'yes':
            tutorial()
            answering = False
        elif command in commands and command == 'no':
            answering = False
        else:
            print("Invalid Command.")
            print("yes or no only")
            command = input("> ")

    os.system('cls')
    #Introduction
    print('''
    Welcome traveller! It has been so long since we've had visitors. My name is King Phillip.
    I'd like to welcome you into the town, but I need to know your name...
    ''')
    #while loop to make sure user enters a valid name; i.e. name not in the commands tuple
    command = input("> ")
    introducing = True
    player = Player("")
    while introducing:
        if command == 'help':
            helps()
            print("I need to know your name if I am to introduce you!")
            command = input("> ")
        elif command == 'developer':
            developer()
            print("I need to know your name if I am to introduce you!")
            command = input("> ")
        elif command in commands:
            print("I don't even know your name yet!")
            command = input("> ")
        else:
            print("Are you sure %s is your name? (Cannot be changed later...)" % command)
            answer = input("> ")
            if answer == 'yes':
                player = Player(command)
                introducing = False
            elif answer == 'no':
                print("Please tell me your name.")
                command = input("> ")
            else:
                print("This is a yes or no question. Please answer with either yes or no")

    save_object(player, 'save.cave')

    #Very primitive story as of now
    print('''
    I'm very glad you are here! There has been some recent disappearances of fellow townspeople over the last
    couple of months. The disappearances only happen when the townspeople venture out of the town.
    I'm worried because we have a network of underground cave systems that were used long ago for purposes you need
    not worry about.''')
    input("Press enter key to continue...")

    print('''
    I think that something is under there terrorizing my citizens and killing them.
    I would go down there but I'm not sure that is much of a King's duty.
    Would you please check it out for me?
    ''')
    print("You have %s" % player.gold)
    print("")
    banner("Rewards 20 Gold")

    command = input("> ")
    answering = True
    while answering:
        if command in commands:
            if command == 'help':
                helps()
                input("Press enter key to continue...")
                os.system('cls')
                os.system('cls')
                print("So, will you help me?")
                print("You have %s" % player.gold)
                banner("Rewards 20 Gold")
                command = input("> ")

            elif command == 'info':
                os.system('cls')
                info(player)
                input("Press enter key to continue...")
                print("So, will you help me?")
                print("You have %s" % player.gold)
                banner("Rewards 20 Gold")
                command = input("> ")

            elif command == 'developer':
                os.system('cls')
                developer()
                input("Press enter key to continue...")
                print("So, will you help me?")
                print("You have %s" % player.gold)
                banner("Rewards 20 Gold")
                command = input("> ")

            elif command == 'yes':
                player.level = 1
                level1(player)
                answering = False

            elif command == 'no':
                print("Oh well... I really thought you would stay and help. You look like the helping type.")
                print("No worries; many have come, many will go.")
                print("Enjoy the rest of your journey!")
                print("(note that this is exiting the game)")
                time.sleep(3)
                exit()
            else:
                print("Not available right now.")
                print("So, will you help me?")
                print("You have %s" % player.gold)
                banner("Rewards 20 Gold")
                command = input("> ")

        else:
            print("Not a valid command. Try again.")
            print("So, will you help me?")
            print("You have %s" % player.gold)
            banner("Rewards 20 Gold")
            command = input("> ")


def check_for_save():
    global command
    global player
    if os.path.exists('save.cave'):
        print("There is a save file in the game directory. Would you like to load it?")
        print("yes - continue progress")
        print("no - new game")
        command = input("> ")
        if command == 'yes':
            load('save.cave')
            print("")
            loaded_data = load('save.cave')
            player = Player(loaded_data.name, loaded_data.gold, loaded_data.health,
                            loaded_data.inventory, loaded_data.state, loaded_data.level)
            player.item_quantities = loaded_data.item_quantities
            player.selected_item = loaded_data.selected_item
            print("File loaded!")
            time.sleep(1)
            info(player)
            time.sleep(2)
            os.system('cls')
            continue_progress(player)
        elif command == 'no':
            introduction()
    else:
        introduction()


def attack(player_obj, monster_obj):
    global command
    m_name = monster_obj[0]
    m_atk = monster_obj[1]
    m_health = monster_obj[2]
    p_name = player_obj.name
    equipped_item = player_obj.selected_item

    print("A %s appears! It has %s HP and deals %s DP" % (m_name, m_health, m_atk))
    print("What would you like to do? (attack (a), flee (f), or use a potion)")
    command = input("> ")
    inputting = True
    while inputting:
        if command == 'attack' or command == 'a':
            attacking = True
            while attacking:
                print("Primary Weapon: %s" % player_obj.selected_item)
                print("")
                print("")
                time.sleep(0.2)
                while player_obj.health >= 0:
                    print("%s - %s HP \t %s - %s HP" % (m_name.capitalize(), m_health, p_name, player_obj.health))
                    if player_obj.health <= 0:
                        print("You've been defeated! Would you like to play again?")
                        command = input("> ")
                        answering = True
                        while answering:
                            if command == 'yes':
                                if os.path.isfile("save.cave"):
                                    introduction()
                                else:
                                    print("Error: file not found.")
                            elif command == 'no':
                                os.remove('save.cave')
                                exit()
                            else:
                                print("You're dead. This is a yes or no question.")
                                command = input("> ")
                    else:
                        if command == 'attack' or command == 'a':
                            if m_health <= 0:
                                player_obj.gold += m_atk
                                print("%s defeated! You've gained %s Gold!" % (m_name.capitalize(), m_atk))
                                save_object(player_obj, 'save.cave')
                                attacking = False
                                inputting = False
                                break
                            print("Attacking.")
                            time.sleep(0.3)
                            print("Attacking..")
                            time.sleep(0.3)
                            print("Attacking...")
                            time.sleep(0.3)
                            print("")
                            random_atk_range = random.randint(0, 1)
                            random_atk_strength = random.randrange(1, m_atk)
                            if m_health >= 0:
                                p_atk = player_obj.item_strengths[equipped_item]
                                if random_atk_range == 0:
                                    player_obj.health -= random_atk_strength
                                    if player_obj.health <= 0:
                                        print("You've been defeated! Would you like to play again?")
                                        print("yes - new game")
                                        print("no - quit game (deletes save file)")
                                        command = input("> ")
                                        answering = True
                                        while answering:
                                            if command == 'yes':
                                                if os.path.isfile("save.cave"):
                                                    introduction()
                                                else:
                                                    print("Error: file not found.")
                                            elif command == 'no':
                                                os.remove('save.cave')
                                                exit()
                                            else:
                                                print("You're dead. This is a yes or no question.")
                                                command = input("> ")

                                    print("Ouch, that hurt...")
                                    print("You lost %s HP" % random_atk_strength)
                                    print("You now have %s HP" % player_obj.health)
                                    save_object(player_obj, 'save.cave')
                                    print("Attack again or Flee?")
                                    command = input("> ")
                                elif random_atk_range == 1:
                                    m_health -= p_atk
                                    print("Nice hit!")
                                    if m_health <= 0:
                                        player_obj.gold += (m_atk + 5)
                                        print("%s defeated! You've gained %s Gold!" % (m_name.capitalize(), m_atk))
                                        save_object(player_obj, 'save.cave')
                                        attacking = False
                                        inputting = False
                                        break
                                    else:
                                        print("%s lost %s HP" % (m_name.capitalize(), p_atk))
                                        print("It now has %s HP" % m_health)
                                        save_object(player_obj, 'save.cave')
                                        print("Attack again or Flee?")
                                        command = input("> ")

                        elif command == 'flee' or command == 'f':
                            flee(player_obj, monster_obj)
                            attacking = False
                            inputting = False
                            break
                        elif 'use' in command:
                            use(command, player_obj)
                            print("%s - %s HP \t %s - %s HP" %
                                  (m_name.capitalize(), m_health, p_name, player_obj.health))
                            print("Attack again or Flee")
                            command = input("> ")
                        else:
                            print("Invalid Command.")
                            print("Attack again or Flee?")
                            command = input("> ")

        elif command == 'flee' or command == 'f':
            flee(player_obj, monster_obj)
            inputting = False
        elif 'use' in command:
            use(command, player_obj)
            print("%s - %s HP \t %s - %s HP" % (m_name.capitalize(), m_health, p_name, player_obj.health))
            print("Attack again or Flee?")
            command = input("> ")
        else:
            print("Invalid Command.")
            command = input("> ")
    player_obj.item_strengths[player_obj.selected_item] = weapons[player_obj.selected_item]
    info(player_obj)


def flee(player_obj, monster_obj):
    print("Fleeing.")
    time.sleep(0.3)
    print("Fleeing..")
    time.sleep(0.3)
    print("Fleeing...")
    time.sleep(0.3)

    m_name = monster_obj[0]
    m_atk = monster_obj[1]
    random_ran = random.randint(0, 4)
    random_gold = random.randrange(1, 5)
    if random_ran == 0 or random_ran == 1 or random_ran == 2:
        player_obj.gold -= random_gold
        print("You successfully ran away.")
        print("However, you dropped %s gold trying to get away." % random_gold)
    else:
        print("%s won't let you get away! Stay and fight!" % m_name.capitalize())
        print("%s attacked you!" % m_name.capitalize())
        player_obj.health -= m_atk
        attack(player_obj, monster_obj)


def banner(text):
    l = (len(text)) + 4
    print("*" * l)
    print("*" + " " + text + " " + "*")
    print("*" * l)


def boss_level(player_obj):
    level_passed = False
    os.system('cls')
    save_object(player_obj, 'save.cave')
    banner("Boss Level!")
    if level_passed:
        print("Congratulations %s! You've cleared the cave system and my people are safe again. Thank you!"
              % player.name)
        time.sleep(4)
        sys.exit(0)


def level4(player_obj):
    level_passed = False
    os.system('cls')
    save_object(player_obj, 'save.cave')
    banner("Level 4")
    time.sleep(0.2)
    if level_passed:
        boss_level(player_obj)


def level3(player_obj):
    level_passed = False
    os.system('cls')
    save_object(player_obj, 'save.cave')
    banner("Level 3")
    time.sleep(0.2)
    if level_passed:
        level4(player_obj)


def level2(player_obj):
    level_passed = False
    os.system('cls')
    save_object(player_obj, 'save.cave')
    banner("Level 2")
    time.sleep(0.2)
    if level_passed:
        level3(player_obj)


def level1(player_obj):
    global command
    global answering

    level_passed = False
    os.system('cls')
    banner("Level 1")
    print("You are on your way to check the caves but before doing so, you need to stop at the shop to buy a weapon.")
    shop(player_obj)
    save_object(player_obj, 'save.cave')
    count = 0
    for item in player_obj.inventory:
        if item in weapons_list:
            count += 1
        elif item in potions_list:
            pass
        else:
            pass
    if count > 0:
        os.system('cls')
        print("Now that you have a weapon, you continue down the path to the caves...")
    else:
        os.system('cls')
        print("You're going to be sorry you didn't buy a weapon!")
    time.sleep(0.3)
    item_select(player_obj)
    print("")
    print('''You finally find the entrance to the cave. As you enter, you notice primitive writing on the walls.
You go deeper into the cave. Along the wall, there are skeletons lined up...''')
    print("Suddenly...")
    input("Press enter key to continue...")
    os.system('cls')
    try:
        monster = create_monster(1)
        attack(player_obj, monster)
        save_object(player_obj, 'save.cave')
        time.sleep(5)
    except KeyError:
        print("You've been defeated already because you didn't buy a weapon.")
        print("Would you like to play again?")
        print("yes - new game (deletes save file)")
        print("no - exit game (preserves save file)")
        command = input("> ")
        answering = True
        while answering:
            if command == 'yes':
                if os.path.isfile("save.cave"):
                    os.remove('save.cave')
                    print("Your save file has been deleted.")
                    answering = False
                    introduction()
                else:
                    print("Error: file not found.")
            elif command == 'no':
                print("Thanks for playing!")
                print("Your save file is still in the directory.")
                time.sleep(1)
                exit()
    sleep(player_obj)
    if level_passed:
        level2(player_obj)

#The first actually executed bit of code. First thing is to check for a save.cave file.
#If it exists, the player is started at the beginning of whatever level they left off.
#They start with their previous inventory and gold as well. If no save.cave, introduction() is invoked.
check_for_save()

Post a Reply

Replies

Oldest  Newest  Rating
0 Mel Addison · December 7, 2014
It did not run correctly for me. But, I may not be doing it correctly. I will look at it later when I have more time. I LOVE adventure games and I used to play a lot of Scott Adams' Adventures in the '70s and 80's.
  • 1

Python

107,307 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator