Advertisement
TorroesPrime

Untitled

Mar 19th, 2022
900
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 20.38 KB | None | 0 0
  1. import os
  2. from classSkill import *
  3. import time
  4. import json
  5. listOfSkills = []
  6. listOfTalents = []
  7. curLocation = os.path.dirname(os.path.abspath(__file__))
  8. settingsFile = os.path.dirname(os.path.abspath(__file__))+"\\settings.json"
  9. defaultSettings = {
  10.     "dir":os.path.dirname(os.path.abspath(__file__))+"\\dataFiles\\output\\",
  11.     "xml":False,
  12.     "csv":True,
  13.     "read format":".csv",
  14.     "other format":".xml",
  15.     "wait": .35
  16. }
  17. title = "  Torroes Prime's Text Adventure Engine Library builder   "    
  18. outputForm = "Current Output format: "
  19. outDirectory = curLocation+"\\dataFiles\\output\\"
  20. outFormat = ".csv"
  21. otherFormat = ".xml"
  22. readFormat = ".csv"
  23. waitValue = .45
  24. lastSkillSourceFile = "list_skills.csv"
  25. lastTalentSourceFile = "list_talents_data.csv"
  26. skillLibraryFile = "library_Skill"+outFormat
  27. talentLibraryFile = "library_Talents"+outFormat
  28. lastSourceDirectory = os.path.dirname(os.path.abspath(__file__))+"\\"
  29.  
  30. def main():
  31.     """method to display main screen and take user selection at top level"""
  32.     global settingsFile
  33.     readSettings(settingsFile)
  34.     options = [f"Create a new {outFormat} library from a {readFormat} file","Change options","Quit program"]
  35.     print(title)
  36.     print("███╗   ███╗ █████╗ ██╗███╗   ██╗    ███╗   ███╗███████╗███╗   ██╗██╗   ██╗")
  37.     print("████╗ ████║██╔══██╗██║████╗  ██║    ████╗ ████║██╔════╝████╗  ██║██║   ██║")
  38.     print("██╔████╔██║███████║██║██╔██╗ ██║    ██╔████╔██║█████╗  ██╔██╗ ██║██║   ██║")
  39.     print("██║╚██╔╝██║██╔══██║██║██║╚██╗██║    ██║╚██╔╝██║██╔══╝  ██║╚██╗██║██║   ██║")
  40.     print("██║ ╚═╝ ██║██║  ██║██║██║ ╚████║    ██║ ╚═╝ ██║███████╗██║ ╚████║╚██████╔╝")
  41.     print("╚═╝     ╚═╝╚═╝  ╚═╝╚═╝╚═╝  ╚═══╝    ╚═╝     ╚═╝╚══════╝╚═╝  ╚═══╝ ╚═════╝ ")
  42.     count = 1
  43.     for key in options:
  44.         print(count," -- ",key)
  45.         count += 1
  46.     selection = int(input("Please type the number of your seleciton: "))
  47.     if selection == 1:
  48.         #call methods to view the screen to create a new skill or talent library entry
  49.         createNewFile()
  50.     elif selection == 2:
  51.         #call methods to view the screen to change serttings
  52.         settings()
  53.     elif selection == 3:
  54.         saveSettings(settingsFile)
  55.         quit()
  56.     else:
  57.         print("That is not a valid selection, dumb ass.")
  58.         main()
  59.  
  60. def settings():
  61.     """method to display settings screen and take user selection to make changes to output format or output directory"""
  62.     print(title)
  63.     print("\n")
  64.     print("\n")
  65.     print("███████╗███████╗████████╗████████╗██╗███╗   ██╗ ██████╗ ███████╗")
  66.     print("██╔════╝██╔════╝╚══██╔══╝╚══██╔══╝██║████╗  ██║██╔════╝ ██╔════╝")
  67.     print("███████╗█████╗     ██║      ██║   ██║██╔██╗ ██║██║  ███╗███████╗")
  68.     print("╚════██║██╔══╝     ██║      ██║   ██║██║╚██╗██║██║   ██║╚════██║")
  69.     print("███████║███████╗   ██║      ██║   ██║██║ ╚████║╚██████╔╝███████║")
  70.     print("╚══════╝╚══════╝   ╚═╝      ╚═╝   ╚═╝╚═╝  ╚═══╝ ╚═════╝ ╚══════╝")
  71.     print("            The current settings are:                  ")
  72.     print("Current Output directory:\n",outDirectory)
  73.     print(f"Current program location is {curLocation}")
  74.     if outFormat == ".xml":
  75.         print(outputForm,".xml")
  76.     else:
  77.         print(outputForm,".csv")
  78.     print("What do you want to do?")
  79.     optionNames = ["Change output directory","Change output format","change input format","Restore Default Settings","Change nothing and return to main menu"]
  80.     optionCount = 0
  81.     for entry in optionNames:
  82.         print(f"  {optionCount+1} -- {entry}")
  83.         optionCount += 1
  84.     selection = "q"
  85.     while selection != len(optionNames):
  86.         selection = int(input("What would you like to do? "))
  87.         if selection == 1:
  88.             #call method to change the output directory
  89.             changeOutputDirectory()
  90.             selection = len(optionNames)
  91.         elif selection == 2:
  92.             #call method to change the output format
  93.             changeFormat()
  94.             selection = len(optionNames)
  95.         elif selection == 3:
  96.             #call method to change input format
  97.             selection = len(optionNames)
  98.             pass
  99.         elif selection == 4:
  100.             #call method to restore default settings
  101.             resetToDefaults()
  102.             time.sleep(waitValue)
  103.             settings()
  104.         elif selection == len(optionNames):
  105.             #call method to display main screen
  106.             main()
  107.         else:
  108.             print("That is not a valid selection, dumb ass.")
  109.             time.sleep(waitValue)
  110.             settings()
  111.  
  112. def changeReadFormat():
  113.     """method to change input format from csv to xml or vice versa"""
  114.     global outFormat
  115.     global otherFormat
  116.     print(title)
  117.     print("╔═╗┬ ┬┌─┐┌┐┌┌─┐┌─┐  ╦┌┐┌┌─┐┬ ┬┌┬┐  ╔═╗┌─┐┬─┐┌┬┐┌─┐┌┬┐")
  118.     print("║  ├─┤├─┤││││ ┬├┤   ║│││├─┘│ │ │   ╠╣ │ │├┬┘│││├─┤ │ ")
  119.     print("╚═╝┴ ┴┴ ┴┘└┘└─┘└─┘  ╩┘└┘┴  └─┘ ┴   ╚  └─┘┴└─┴ ┴┴ ┴ ┴ ")
  120.     print(f"Currently the output format is set to {outFormat} format. Do you with to change it to {otherFormat}? Type 'Y' to confirm or 'N' to abort.")
  121.     userConfirmation = input()
  122.     if userConfirmation.lower() == "y":
  123.         outFormat, otherFormat = otherFormat,outFormat
  124.         print(f" The outformat has been changed to {outFormat}")
  125.         time.sleep(settings["wait"])
  126.         main()
  127.  
  128. def changeFormat():
  129.     """method to change output format from csv to xml or vice versa"""
  130.     global outFormat
  131.     global otherFormat
  132.     print(title)
  133.     print("╔═╗┬ ┬┌─┐┌┐┌┌─┐┌─┐  ╔═╗┬ ┬┌┬┐┌─┐┬ ┬┌┬┐  ╔═╗┌─┐┬─┐┌┬┐┌─┐┌┬┐")
  134.     print("║  ├─┤├─┤││││ ┬├┤   ║ ║│ │ │ ├─┘│ │ │   ╠╣ │ │├┬┘│││├─┤ │ ")
  135.     print("╚═╝┴ ┴┴ ┴┘└┘└─┘└─┘  ╚═╝└─┘ ┴ ┴  └─┘ ┴   ╚  └─┘┴└─┴ ┴┴ ┴ ┴ ")
  136.     print(f"Currently the output format is set to {outFormat} format. Do you with to change it to {otherFormat}? Type 'Y' to confirm or 'N' to abort.")
  137.     userConfirmation = input()
  138.     if userConfirmation.lower() == "y":
  139.         outFormat, otherFormat = otherFormat,outFormat
  140.         print(f" The outformat has been changed to {outFormat}")
  141.         time.sleep(waitValue)
  142.     else:
  143.         settings()
  144.     settings()
  145.        
  146. def changeOutputDirectory():
  147.     global outDirectory
  148.     """method to change the output directory to the supplied directory."""
  149.     print("\n\n\n\n")
  150.     print(title)
  151.     print("╔═╗┬ ┬┌─┐┌┐┌┌─┐┌─┐  ╔═╗┬ ┬┌┬┐┌─┐┬ ┬┌┬┐  ╔╦╗┬┬─┐┌─┐┌─┐┌┬┐┌─┐┬─┐┬ ┬")
  152.     print("║  ├─┤├─┤││││ ┬├┤   ║ ║│ │ │ ├─┘│ │ │    ║║│├┬┘├┤ │   │ │ │├┬┘└┬┘")
  153.     print("╚═╝┴ ┴┴ ┴┘└┘└─┘└─┘  ╚═╝└─┘ ┴ ┴  └─┘ ┴   ═╩╝┴┴└─└─┘└─┘ ┴ └─┘┴└─ ┴ ")
  154.     print("Current Output directory:",outDirectory)
  155.     newDirectory = input("Please type in the directory you would like to change the output directory to or simply press enter to return to the main menu:")
  156.     if newDirectory != "":
  157.         try:
  158.             os.chdir(newDirectory)
  159.             print("Current working directory: {0}".format(os.getcwd()))
  160.             outDirectory = newDirectory
  161.             time.sleep(waitValue)
  162.         except FileNotFoundError:
  163.             print("Directory: {0} does not exist".format(newDirectory))
  164.             time.sleep(settings["wait"])
  165.         except NotADirectoryError:
  166.             print("{0} is not a directory".format(newDirectory))
  167.             time.sleep(settings["wait"])
  168.         except PermissionError:
  169.             print("You do not have permissions to change to {0}".format(newDirectory))
  170.             time.sleep(settings["wait"])
  171.     main()
  172.  
  173. def checkFileFormat(fileName):
  174.     """method to call indicated read method based on the extenstion of the supplied filename """
  175.     pass
  176.  
  177. def resetToDefaults():
  178.     """method to put program settings back to defaults"""
  179.     global outDirectory
  180.     global outFormat
  181.     global otherFormat
  182.     global readFormat
  183.     global waitValue
  184.     global settingsFile
  185.     outDirectory = defaultSettings["dir"]
  186.     outFormat = ".csv"
  187.     otherFormat = defaultSettings["other format"]
  188.     readFormat = defaultSettings["read format"]
  189.     waitValue = defaultSettings["wait"]
  190.     saveSettings(settingsFile)
  191.  
  192. def readXmlFile(fileName):
  193.     """method to open supplied xml file name and read the contents into a list of lines, then returns to that list to calling entity. Displays an error if a csv file is supplied."""
  194.     pass
  195.  
  196. def readcsvFile(fileName):
  197.     """method to open supplied csv file name and read the contents into a list of lines, then returns to that list to calling entity. Displays an error if an xml file is supplied."""
  198.     dataList = []
  199.     with open(fileName,'r') as src:
  200.         dataList = src.readlines()
  201.         return dataList
  202.  
  203. def checkDir(directory):
  204.     """method to check if a supplied directory exists and if not, calls the getNewDirectory method to prompt the user to provide a new directory."""
  205.     if directory[-1] != "\\":
  206.         directory+= "\\"
  207.     while os.path.isdir(directory) == False:
  208.         print(f"directory: \"{directory}\" not found.")
  209.         directory = getNewDirectory()
  210.         if directory[-1] != "\\":
  211.             directory+= "\\"
  212.     return directory
  213.  
  214. def checkFile(fileName,directory):
  215.     """method to check if supplied filenamme exists in supplied directory. Returns boolean"""
  216.     if fileName in os.listdir(directory):
  217.         return True
  218.     else:
  219.         return False
  220.  
  221. def createNewFile():
  222.     print("\n\n\n\n\n")
  223.     print(title)
  224.     print("  o-o              o          o   o                  o--o   o     ")
  225.     print(" /                 |          |\ |                  |    o |     ")
  226.     print("O     o-o o-o  oo -o- o-o     | \ | o-o o   o   o    O-o    | o-o ")
  227.     print(" \   |   |-' | |  |  |-'     |  \| |-'  \ / \ /     |    | | |-' ")
  228.     print("  o-o o   o-o o-o- o  o-o     o   o o-o   o   o      o    | o o-o ")
  229.     options = ["Create a new skills library file","Create a new talents library file","Change settings","Do nothing and return to the main menu"]
  230.     print("Current Output directory:\n",outDirectory)
  231.     print(f"Current Output format is {outFormat}")
  232.     count = 1
  233.  
  234.     for option in options:
  235.         print( count,"  --  ",option)
  236.         count += 1
  237.     userSelection = "q"
  238.     while str(type(userSelection)) != "<class 'int'>":
  239.         userSelection = int(input("Ente the number of your desired operation:"))
  240.         if userSelection == 1:
  241.             #call method to create a new skills library file
  242.             makeNewFile(False)
  243.            
  244.         elif userSelection == 2:
  245.             #call method to create a new talents library file
  246.             makeNewFile(True)
  247.         elif userSelection == 3:
  248.             #call main method.
  249.             settings()
  250.             userSelection = 4
  251.         elif userSelection == 4:
  252.             #call main method.
  253.             main()
  254.         else:
  255.             print("That is an invalid selecton. Try reading next time, okay?")
  256.             createNewFile()
  257.  
  258. def makeNewSkills(listOfLines):
  259.     """method to take a list of lines and compile a new list of skill objects based on the contents of the supplied file. returns list to calling entity"""
  260.     for entry in listOfLines:
  261.         data = entry.split(",")
  262.         newEntry = ""
  263.         if "[]" in data[0]:
  264.             newEntry = newSkillGroup(data)
  265.         else:
  266.             newEntry = newSkill(data)
  267.         if str(type(newEntry)) == "<class 'classSkill.skill'>":
  268.             listOfSkills.append(skill(newEntry))
  269.         elif str(type(newEntry)) == "<class 'list'>":
  270.             for entry in newEntry:
  271.                 listOfSkills.append(skill(entry))
  272.  
  273. def writecsvFile(listOfData,csvFileToWriteTo):
  274.     data = ""
  275.     with open(csvFileToWriteTo,'w') as out:
  276.         for item in listOfData:
  277.             entryListing = item.getData():
  278.             for datum in entryListing:
  279.                 data += datum+","
  280.             out.write(data)
  281.  
  282. def newSkill(lineOfData):
  283.     """method to take a list of lines, and create a single new skill object."""
  284.     n = lineOfData[0]
  285.     a = lineOfData[1]
  286.     c =lineOfData[2]
  287.     t =lineOfData[3]
  288.     d = lineOfData[4]
  289.     newSkillItem = skill(name=n,advanced=a,characteristic=c,testType=t,description=d)
  290.     return newSkillItem
  291.  
  292. def newSkillGroup(listOfData):
  293.     """method to take a list of lines, and create a list containing the data for a group of skills. returns a list of lines"""
  294.     skillItems = []
  295.     name = listOfData[0][:-2]
  296.     advanced = listOfData[1]
  297.     characteristic =listOfData[2]
  298.     testType =listOfData[3]
  299.     description = listOfData[4]
  300.     for key in groups["skills"][name.lower()]:
  301.         skillGroupName = name+"("+key+")"
  302.         skillItems.append(skill(skillGroupName,advanced,characteristic,testType,description))
  303.     return skillItems
  304.  
  305. def makeNewTalents(listOfLines):
  306.     pass
  307.  
  308. def saveSettings(settingsFile):
  309.     """method to write the programs settings to an external files so they are saved between uses"""
  310.     global outDirectory
  311.     global outFormat
  312.     global otherFormat
  313.     global readFormat
  314.     global waitValue
  315.     global lastSkillSourceFile
  316.     global  lastTalentSourceFile
  317.     settings = {    
  318.         "dir":outDirectory,
  319.         "outFormat":outFormat,
  320.         "otherFormat":otherFormat,
  321.         "read format":readFormat,
  322.         "wait": waitValue,
  323.         "skills source file":lastSkillSourceFile,
  324.         "talents source file":lastTalentSourceFile,
  325.         "last source directory":lastSourceDirectory
  326.         }
  327.     with open(settingsFile,'w') as s:
  328.         s.write(json.dumps(settings))
  329.  
  330. def readSettings(settingsFile):
  331.     """method to read the settings file and apply those settings to the current values"""
  332.     with open(settingsFile,'r') as src:
  333.         for line in src.readlines():
  334.             readData = json.loads(line)
  335.             global outDirectory
  336.             global outFormat
  337.             global otherFormat
  338.             global readFormat
  339.             global waitValue
  340.             global lastSkillSourceFile
  341.             global lastTalentSourceFile
  342.             global lastSourceDirectory
  343.             #outDirectory = readData["dir"]
  344.             outFormat = readData["outFormat"]
  345.             otherFormat = readData["otherFormat"]
  346.             readFormat = readData["read format"]
  347.             waitValue = readData["wait"]
  348.             lastSkillSourceFile = readData["skills source file"]
  349.             lastTalentSourceFile =readData["talents source file"]
  350.             lastSourceDirectory = readData["last source directory"]
  351.  
  352. def newFile():
  353.     print(title)
  354.     print("███╗   ██╗███████╗██╗    ██╗    ███████╗██╗██╗     ███████╗")
  355.     print("████╗  ██║██╔════╝██║    ██║    ██╔════╝██║██║     ██╔════╝")
  356.     print("██╔██╗ ██║█████╗  ██║ █╗ ██║    █████╗  ██║██║     █████╗  ")
  357.     print("██║╚██╗██║██╔══╝  ██║███╗██║    ██╔══╝  ██║██║     ██╔══╝  ")
  358.     print("██║ ╚████║███████╗╚███╔███╔╝    ██║     ██║███████╗███████╗")
  359.     print("╚═╝  ╚═══╝╚══════╝ ╚══╝╚══╝     ╚═╝     ╚═╝╚══════╝╚══════╝")
  360.     print("                                                           ")
  361.     options = ["Create a new skills library file","Create a new Talents library file","Do nothing and return to the main menu"]
  362.     optionNum = 1
  363.     for entry in options:
  364.         print(f"   {optionNum} -- {entry}")
  365.         optionNum += 1
  366.     selection = "q'"
  367.     while selection != 'x':
  368.         selection = int(input("What would you like to do? "))
  369.         if selection == 1:
  370.             makeNewFile(False)
  371.             main()
  372.            # selection = 3
  373.         elif selection == 2:
  374.             makeNewFile(True)
  375.             selection = 3
  376.         elif selection == 3:
  377.             main()
  378.             selection = 3
  379.         else:
  380.             print("That is not a valid selection, dumb ass.")
  381.  
  382. def readFile(fileName):
  383.     content = ""
  384.     if readFormat == ".csv":
  385.         content = readcsvFile(fileName)
  386.     else:
  387.         content = readXmlFile(fileName)
  388.     return content
  389.  
  390. def makeNewFile(talent=True):
  391.     global lastSourceDirectory
  392.     global lastSkillSourceFile
  393.     global lastTalentSourceFile
  394.     fullSource=lastSourceDirectory
  395.     if talent == False:
  396.         readFileType = "skills"
  397.         source = lastSkillSourceFile
  398.     else:
  399.         readFileType = "talents"
  400.         source = lastTalentSourceFile
  401.     print(f"Last time you built a {readFileType} library, you read a file named {source} located in {lastSourceDirectory}. Do you want to use that same file? Type 'Y' to confirm. Type 'N' to supply a different file name.")
  402.     userSelection = input()
  403.     if userSelection.lower() == "n":
  404.         source = input("Please provide the name of the file you wish to read in from: ")
  405.         dirLocation = checkDir(lastSourceDirectory)
  406.         goodCheck = checkFile(source,dirLocation)
  407.         print("goodCheck: ",goodCheck)
  408.         while  goodCheck == False:
  409.             print(f"A file named \"{source}\" was not found in {dirLocation}. Is it somewhere else? Type 'Y' to supply an alternate directory.")
  410.             userResponse = input()
  411.             if userResponse.lower() != "y":
  412.                 print("I'm sorry. You should double check the file name and the location. Returning to the main menu.")
  413.                 time.sleep(waitValue)
  414.                 main()
  415.             else:
  416.                 newDirectory = getNewDirectory()
  417.                 goodCheck = checkFile(source,newDirectory)
  418.                 dirLocation = newDirectory
  419.                 fullSource = newDirectory+source
  420.     fullSource =dirLocation+source
  421.     if talent == True:
  422.         lastTalentSourceFile = source
  423.         makeNewTalents(readFile(fullSource))
  424.     elif talent == False:
  425.         lastSkillSourceFile = source
  426.         makeNewSkills(readFile(fullSource))
  427.         writecsvFile(listOfSkills,outDirectory+"dataSkills.csv")
  428.     for entry in listOfSkills:
  429.         print(entry)
  430.     saveSettings(settingsFile)
  431.     newFile()
  432.  
  433. def getNewDirectory():
  434.     """askes the user for a new directory and returns the string to the calling entity"""
  435.     newDirectory = input("Please type the full directory: ")
  436.     return newDirectory
  437.  
  438. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement