I am working on a text-based adventure game and I'm implementing new features, one of these features being saves and loads. This code works, and I know that there is a more efficient way of coding it, but this is sufficient. I will first post the code (feel free to play with it, but bear in mind that this is only the beginning of the game, and I have not yet started on the fighting and weapons etc.), and I will then post the saving and loading functions.
Keep in mind that it creates the save file in the same directory as the .py, I will explain later how to save them and load them from a separate directory.
#imports
import random
import sys
import time
import pickle
#Player Class
class Player:
def __init__(self, name):
self.name = name
self.maxhealth = 100
self.health = self.maxhealth
self.attack = 15
self.money = 0
def display(self, name):
print("Name:",self.name,"\nHealth:",self.health,"/",self.maxhealth,"\nAttack Damage:",self.attack,"\nMoney:",self.money)
#Enemy Class
class Dragon:
def __init__(self, name):
self.name = name
self.maxhealth = 150
self.health = self.maxhealth
self.attack = 5
#Start
def main():
print("Welcome to The Ultimate Dragon fighter RPG!")
print("1] Start")
print("2] Load")
print("3] Profile")
print("4] Exit")
option = input("--> ").upper()
if option == "1" or option == "S" or option == "START":
nameInputAsk()
elif option == "2" or option == "L" or option == "LOAD":
load()
nameInputAsk()
elif option == "3" or option == "P" or option == "PROFILE":
stats()
elif option == "4" or option == "E" or option == "EXIT":
print("Goodbye!")
time.sleep(2)
sys.exit()
else:
main()
#User Inputs IG Name
def nameInputAsk():
print("Hello! What do you want your name to be?")
option = input("--> ")
global PlayerIG
PlayerIG = Player(option)
print("Oh nice! That's a cool name %s!" % PlayerIG.name)
#time.sleep(2)
print("Personally I would have gone for something like \'SuperAwesomeBattleFighter\' but I guess that's your loss.")
nameChangeAsk()
#User changes name
def nameChangeAsk():
name_input = input("Do you want to change your name?\n1] Yes\n2] No\n--> ")
if name_input == "y" or name_input == "Y" or name_input == "yes" or name_input == "Yes" or name_input == "1" or name_input == "YES":
option = input("Enter your new name:\n--> ")
global PlayerIG
PlayerIG = Player(option)
print("%s. Yes, that's better; it has a nice ring to it." % PlayerIG.name)
statInputAsk()
#User answered "no"
elif name_input == "n" or name_input == "N" or name_input == "no" or name_input == "No" or name_input == "2" or name_input == "NO":
print("Okay. Keep in mind that you won't be able to change your name later!")
statInputAsk()
else:
print("Sorry, that does not compute with me! Please try again!")
nameChangeAsk()
def statInputAsk():
check_input = input("Do you want to see your stats %s?\n1] Yes\n2] No\n--> " % PlayerIG.name)
if check_input == "y" or check_input == "Y" or check_input == "yes" or check_input == "Yes" or check_input == "1":
stats()
elif check_input == "n" or check_input == "N" or check_input == "no" or check_input == "No" or check_input == "2":
print("Oh. Okay then. That's cool. I'll ask again later if you want to see them.")
userMultiChoice()
else:
print("Sorry, that does not compute with me! Please try again!")
statInputAsk()
def stats():
print("Name: %s" % PlayerIG.name)
print("Attack Damage: %d" % PlayerIG.attack)
print("Health: %i/%i" % (PlayerIG.health, PlayerIG.maxhealth))
print("Money: %d" % PlayerIG.money)
userMultiChoice()
def userMultiChoice():
option = input("What do you want to do?\n1] See your blance. \n2] Go to the shop. \n3] Go on an adventure.\n--> ")
if option == "1" or option == "balance" or option == "Balance" or option == "BALANCE":
print("Money: %d" % PlayerIG.money)
elif option == "2" or option == "shop" or option == "Shop" or option == "SHOP" or option == "store" or option == "Store" or option == "STORE":
pass
elif option == "3" or option == "adventure" or option == "Adventure" or option == "ADVENTURE" or option == "go" or option == "Go" or option == "GO":
adventuringMarshMount()
else:
print("Sorry, that does not compute with me! Please try again!")
userMultiChoice()
#Marshlands or Mountains - Random
def adventuringMarshMount():
askSave()
print("You walk outside your home and head down a path.")
print("""You suddenly come across a fork in the path, and cannot make a decision
whether to go left or right to the marshlands or the mountains,
so you close your eyes and spin around and let fate decide...""")
time.sleep(10)
spinMarshMount = ""
while spinMarshMount == "":
print("You start to feel dizzy, so you slow down to a stop and open your eyes to see...")
time.sleep(5)
spinMarshMount = random.choice(["marsh", "mount"])
if spinMarshMount == "marsh":
print("the marshlands!")
randomDragonAppear()
else:
print("the mountains!")
time.sleep(1)
print("You start to walk down the path to the mountains until...")
time.sleep(3)
randomDragonAppear()
break
#Dragon, no Dragon - Random
def randomDragonAppear():
print("you hear a crunch behind you")
time.sleep(2)
drag_appear = ""
while drag_appear == "":
print("You turn around and...")
time.sleep(2)
drag_appear = random.choice(["true", "false"])
if drag_appear == "true":
print("THERE IS A DRAGON!")
dragonRunFight()
else:
print("the noise was only a Pigeon. Pesky things.")
break
def askSave():
ask = input("Do you want to save?\n--> ").upper()
if ask == "Y" or ask == "YES":
Save = Player(PlayerIG.name)
#date = time.strftime("%d %b %Y", time.localtime())
pickle.dump(Save, open("Save File", "wb"))
elif ask == "N" or ask == "NO":
print("Okay, maybe next time!")
return
else:
print("Sorry, that does not compute with me! Please try again!")
askSave()
def load():
#date = time.strftime("%d %b %Y", time.localtime())
me = pickle.load(open("Save File","rb"))
me.display(Player.display)
return dragonRunFight()
def dragonRunFight():
print("You can choose to either turn and run like a coward or fight the majestic beast like a man.")
fight = input("Run or Fight?:\n--> ").upper()
if fight == "R" or fight == "RUN":
print("You ran.")
main()
Player's class:
class Player:
def __init__(self, name):
self.name = name
self.maxhealth = 100
self.health = self.maxhealth
self.attack = 15
self.money = 0
The Saving Function:
def askSave():
ask = input("Do you want to save?\n--> ").upper()
if ask == "Y" or ask == "YES":
Save = Player(PlayerIG.name) #Saves the desired class AND a chosen attribute
pickle.dump(Save, open("Save File", "wb")) #Creates the file and puts the data into the file
#The file doesn't have an extension because it is a binary file and makes it easier to parse.
elif ask == "N" or ask == "NO":
print("Okay, maybe next time!")
return
else:
print("Sorry, that does not compute with me! Please try again!")
askSave()
The Loading Function:
def load():
me = pickle.load(open("Save File","rb")) #Loads the file
me.display(Player.display) #Prints the stats out to verify the load has successfully happened
return dragonRunFight()