Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Welcome to... THE RANDOMIZER
- #Created by Noah Fields in November 2018 (over many days)
- #Create Project Final for CSCI 101, though I expect I will expand it in my own time eventually.
- from random import randrange
- from time import sleep
- choices = []
- def start():
- #Print out introductory text, return none
- print("Greetings, mortal. You may not see me, but you shall know that I am here.")
- print("My name is Kordalshaan. I am the digital dragon, and I am here to assist you with the sorting and selecting of your lists.")
- print("Please, direct me to a text file and I shall help you in all ways that I may. \n")
- return None
- def choose_file():
- #Forever
- while True:
- #Attempt to open the file and return it
- try:
- file = open(input("What is the path of the file you would like to open?"), "r+", encoding='windows-1252')
- return file
- #if failure, try again
- except:
- print("Please try again, mortal.")
- #Most of the list elements ended up with a newline at the end of them, which I did not want. This is a slightly longer and more complex
- #way to resolve that than I feel should really be *necessary* but every other way I tried did not work for some reason, including "for item in list_to_choose_from".
- def newline_strip(list_to_strip):
- for x in range(0, len(list_to_strip)):
- if list_to_strip[x].endswith('\n'):
- list_to_strip[x] = list_to_strip[x][0:-1]
- return list_to_strip
- #List everything Kordalshaan the metal dragon can do for you, fine user!
- def help():
- print('''Here is a list of every command which I can do. Commands are not case-sensitive.
- Add: Adds a new entry to the end of the list.
- Exit: Close the program and leave me in this horrifying, terrible state of limbo for a while. Heh, just kidding, I'll be rockin' out while you're gone. Importantly, though, you MUST type Exit for the file to save what you just did. Again - YOU MUST TYPE EXIT FOR THE FILE TO SAVE. DO NOT JUST CLOSE THE TERMINAL.
- Help: Shows a list of available commands. Of course, you probably figured that one out.
- Kordalshaan: Get some information about me, Kordalshaan the digital dragon!
- Open: Open a new text file. This will automatically save and close the old one.
- Random: Get a random item from the list. This is the main command which I can do - the whole reason I am here, is for this purpose. I can tell you more - see 'Kordalshaan'
- Remove: Remove an item from the list. I shall consume it and it will taste good.
- Show: Show the item at one specific position. This uses the range from 1 to the number of items in range.
- Swap: Swap the positions of two items in the list.
- List: Show the entire list, numbered all fancily.''')
- return None
- #Get input from user for new list element. If confirmed, add to list. Will *not* check for duplicates - I can't make this too crazy, I have a whole other project to do for 261 after all. Maybe I'll add that another time
- #Return none, as lists are pass by reference
- def add(working_list):
- item_to_add = input("What would you like to add? It will be pushed to the end of the list.")
- are_you_sure = input("You would like to add " + item_to_add + " to the end of the list. Correct? Press Y for yes, anything else for no. Not case sensitive.").lower()
- if (are_you_sure == 'y'):
- working_list.append(item_to_add)
- print("It has been done!")
- else:
- print("If that is your preference, mortal.")
- return None
- #Clear the contents of the file and then rewrite them, then close the file.
- def close_file(file, working_list):
- file.seek(0)
- file.truncate()
- for line in working_list[0:-1]:
- file.write(line + "\n")
- file.write(working_list[-1])
- file.close()
- return None
- '''
- (__)
- (oo) Oooh, a cow.
- /-------\/ Wonder how that got in here. *shrug* Well, she can stay. She's chummy with Kordalshaan.
- / | ||
- * ||----||
- ^^ ^^
- '''
- #Select something at random from the list. Prints it out super slow, for fun.
- def random_choice(working_list):
- print("All right, mortal. I shall choose an element from your list at random.")
- print("This is the original purpose this program had, you know. Ah, what wondrous concepts...")
- print ("Your choice has been made. You have been granted...", end='')
- sleep(4)
- selection =(working_list[randrange(len(working_list) - 1 )])
- for letter in selection:
- print (letter, end='')
- sleep(1)
- return None
- def get_index(working_list, operation_string):
- return int(input("Which item would you like to " + operation_string + "? The first item in the list is at 1 and it moves on from there.")) -1
- #Remove the item at index i + 1. If that's too far or otherwise is not possible, say so and end the function.
- def remove(working_list):
- remove_index = get_index(working_list, "remove")
- try:
- are_you_sure = input("You would like to remove " + working_list[remove_index] + " from the list. Type Y for yes, anything else for no. Not case-sensitive.").lower()
- if (are_you_sure == 'y'):
- print(working_list[remove_index] + " has been removed.")
- working_list.pop(remove_index)
- except:
- print("That is not possible, mortal.")
- finally:
- return None
- #Get user input i, show item at index i - 1. If i - 1 is not in range, say so and pass. Return none.
- #There's definitely some refactoring I could do to encapsulate shared code between show and remove,
- #But I don't want to spend too much more time than necessary on this since I have other work to do. Gains would be *extremely* minimal anyway.
- def show(working_list):
- show_index = get_index(working_list, "show")
- try:
- print("The element at position " + str(show_index + 1) + " is: " + working_list[show_index])
- except:
- print("That is not possible, mortal.")
- finally:
- return None
- #Swap the positions of two values in the list. Now that I think about it there may be a built-in function for that but whatever.
- def swap(working_list):
- swap_1 = int(input("What is the position of the first value you would like to swap?")) - 1
- swap_2 = int(input("What is the position of the second value you would like to swap?")) - 1
- try:
- temp_list_item = working_list[swap_1]
- working_list[swap_1] = working_list[swap_2]
- working_list[swap_2] = temp_list_item
- print("It has been done, mortal.")
- except:
- print("That is not possible, mortal.")
- finally:
- return None
- #Show each element in the list, with fun numbers and stuff.
- def view(working_list):
- print("The list is as follows: \n" )
- for i in range (0, len(working_list)):
- print(str(i + 1) + ": " + working_list[i]);
- return None
- #Kordalshaan's backstory. ASCII art "Ith, the Purple Dragon" found at the following link: https://www.asciiart.eu/mythology/dragons
- #Used in accordance with the site's permissions and requests. The name of the artist remains on the art, though I have removed
- #the name of the artwork itself since it includes the name of a different dragon (just pretend this is Kordalshaan, 'k?) Special thanks to James Goodwin,
- #your art rocks. He's got a bunch more dragons on the page and they're all amazing.
- def kordalshaan():
- print("Ah, so you are interested in me. I am glad to hear it. Well, my tale starts some time ago...\n\n"
- + "In early 2017, to be precise. I was called into this world by one denizen of the lands of the internet. He is a strange figure, "
- + "one who spends much of this time at his computer. His original purpose for summoning me was to help him with the selection of music. "
- + "For, yes, I was originally a bot on Discord, whose purpose was to serve up the greatest metal tunes by parsing them on Youtube. "
- + "Later, I was granted a job in several short stories he wrote. That... was a weird time. I'd rather not talk too much about that thing."
- + " Suffice it to say that there were salads, walruses, the Banach-Tarski paradox, and a creature from Dungeons and Dragons that looks like a wolf with wings"
- + " that got in the way of a Jackson Pollock drip painting. Ah, the halcyon days of my youth...\n\n"
- + "Now, I find myself presiding of this program, so called THE RANDOMIZER 2.0. I am here to serve you, user, and that is what I shall do."
- + " Of course, if my creator decides in the future that I shall be used for another program, I shall find myself there, diligent as ever."
- + " It's a tough life, but rewarding. And now... let me show you a picture of myself, drawn by James Goodwin. Flattering, is it not? \n\n")
- print( '''
- (`-.
- \ `
- /) , '--. \ `
- // , ' \/ \ ` `
- // ,' ./ /\ \>- ` ,----------.
- ( \ ,' .-.-._ / ,' /\ \ . ` `.
- \ \' /.--. .) ./ ,' / \ . ` `.
- \ -{/ \ .) / / / ,' \ ` `-----. \
- <\ ) ).:) ./ /,' ,' \ `. /\) `. \
- >^, // /..:) / //--' \ `( ) )
- | ,'/ /. .:) / (/ \ \ / /
- ( |(_ (...::) ( \ .-.\ / ,'
- (O| / \:.::) /\ ,' \) / ,'
- \|/ /`.:::) ,/ \ / ( /
- / /`,.:) ,'/ )/ \ \
- ,' ,'.' `:>-._._________,<;' (/ (,'
- ,' / | `^-^--^--^-^-^-'
- .--------' / |
- ( .----' |
- \ <`. \ |
- \ \ `. \ | g o o d w i n
- \ \ `.`. |
- \ \ `.`. |
- \ \ `.`. |
- \ \ `.`.|
- \ \ `.`.
- \ \ ,^-'
- \ \ |
- `.`. |
- .`.|
- `._>'''
- )
- '''Things I could do (but let's face it I need to work on the 261 final come on):
- 1: Write it so that some commands that require additional input, work if user enters
- it all at once. For instance, typing "show 3" would skip the request for item to show and simply
- show the third item (at index 2, because 0-indexing.
- 2: Set it up so that the list cannot contain duplicates. If you try to enter a duplicate, you can't.
- 3: Have the program create the file if no such file exists. As it stands you will have to create
- a blank text file outside of the program if you want to start a blank list.
- 4: Remove, swap, etc. elements by content rather than by index - so, "remove foobar" instead of "remove 2".
- 5: Show the index of an element - so, "index foobar" would show the position of foobar if foobaris in the list
- '''
- def main():
- start()
- #Request file path for first file
- file = choose_file()
- working_list = newline_strip(file.readlines())
- print('\nNow, you may request of me whatever you like. If I am capable of it, I shall carry it out. Type "help" for a list of things which I can do.\n')
- #Forever
- while True:
- #User may input one of: help, view, show [x], add, remove, random, open, kordalshaan, exit, swap
- choice = input("What would you like to do, mortal?").lower()
- if choice == "help":
- help()
- elif choice == "add":
- add(working_list)
- elif choice == "exit":
- close_file(file, working_list)
- print("I will see you another time, mortal. Onwards to glory, my friend!")
- sleep(1.5)
- break
- elif choice == "open":
- #If choice is open, close the file and open a new one. I know this could be encapsulated better but I was dealing with weird behavior and, well... I don't wanna.
- close_file(file, working_list)
- file = choose_file()
- working_list = newline_strip(file.readlines())
- elif choice == "random":
- random_choice(working_list)
- elif choice == "remove":
- remove(working_list)
- elif choice == "show":
- show(working_list)
- elif choice == "swap":
- swap(working_list)
- elif choice == "list":
- view(working_list)
- elif choice == "kordalshaan":
- kordalshaan()
- print("\n")
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement