SHARE
TWEET

Untitled

a guest Dec 8th, 2019 102 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from story.story_manager import *
  2. from generator.gpt2.gpt2_generator import *
  3. from story.utils import *
  4. from termios import tcflush, TCIFLUSH
  5. import time, sys, os
  6. os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
  7.  
  8. def select_game():
  9.     with open(YAML_FILE, 'r') as stream:
  10.         data = yaml.safe_load(stream)
  11.  
  12.     print("Pick a setting.")
  13.     settings = data["settings"].keys()
  14.     for i, setting in enumerate(settings):
  15.         print_str = str(i) + ") " + setting
  16.         if setting == "fantasy":
  17.             print_str += " (recommended)"
  18.  
  19.         console_print(print_str)
  20.     console_print(str(len(settings)) + ") custom")
  21.     choice = get_num_options(len(settings)+1)
  22.  
  23.     if choice == len(settings):
  24.  
  25.         context = ""
  26.         console_print("\nEnter a prompt that describes who you are and the first couple sentences of where you start "
  27.                       "out ex:\n 'You are a knight in the kingdom of Larion. You are hunting the evil dragon who has been " +
  28.                       "terrorizing the kingdom. You enter the forest searching for the dragon and see' ")
  29.         prompt = input("Starting Prompt: ")
  30.         return context, prompt
  31.  
  32.     setting_key = list(settings)[choice]
  33.  
  34.     print("\nPick a character")
  35.     characters = data["settings"][setting_key]["characters"]
  36.     for i, character in enumerate(characters):
  37.         console_print(str(i) + ") " + character)
  38.     character_key = list(characters)[get_num_options(len(characters))]
  39.  
  40.     name = input("\nWhat is your name? ")
  41.     setting_description = data["settings"][setting_key]["description"]
  42.     character = data["settings"][setting_key]["characters"][character_key]
  43.  
  44.     context = "You are " + name + ", a " + character_key + " " + setting_description + \
  45.               "You have a " + character["item1"] + " and a " + character["item2"] + ". "
  46.     prompt_num = np.random.randint(0, len(character["prompts"]))
  47.     prompt = character["prompts"][prompt_num]
  48.  
  49.     return context, prompt
  50.  
  51. def instructions():
  52.     text = "\nAI Dungeon 2 Instructions:"
  53.     text += '\n Enter actions starting with a verb ex. "go to the tavern" or "attack the orc."'
  54.     text += '\n To speak enter \'say "(thing you want to say)"\' or just "(thing you want to say)" '
  55.     text += '\n\nThe following commands can be entered for any action: '
  56.     text += '\n  "revert"   Reverts the last action allowing you to pick a different action.'
  57.     text += '\n  "quit"     Quits the game and saves'
  58.     text += '\n  "restart"  Starts a new game and saves your current one'
  59.     text += '\n  "save"     Makes a new save of your game and gives you the save ID'
  60.     text += '\n  "load"     Asks for a save ID and loads the game if the ID is valid'
  61.     text += '\n  "print"    Prints a transcript of your adventure (without extra newline formatting)'
  62.     text += '\n  "help"     Prints these instructions again'
  63.     return text
  64.  
  65. def play_aidungeon_2():
  66.  
  67.     console_print("AI Dungeon 2 will save and use your actions and game to continually improve AI Dungeon."
  68.                   + " If you would like to disable this enter 'nosaving' for any action. This will also turn off the "
  69.                   + "ability to save games.")
  70.  
  71.     upload_story = True
  72.  
  73.     print("\nInitializing AI Dungeon! (This might take a few minutes)\n")
  74.     generator = GPT2Generator()
  75.     story_manager = UnconstrainedStoryManager(generator)
  76.     print("\n")
  77.  
  78.     with open('opening.txt', 'r') as file:
  79.         starter = file.read()
  80.     print(starter)
  81.  
  82.     while True:
  83.         if story_manager.story != None:
  84.             del story_manager.story
  85.  
  86.         print("\n\n")
  87.         context, prompt = select_game()
  88.         console_print(instructions())
  89.         print("\nGenerating story...")
  90.  
  91.         story_manager.start_new_story(prompt, context=context, upload_story=upload_story)
  92.  
  93.         print("\n")
  94.         console_print(str(story_manager.story))
  95.         while True:
  96.             tcflush(sys.stdin, TCIFLUSH)
  97.             action = input("> ")
  98.             if action == "restart":
  99.                 rating = input("Please rate the story quality from 1-10: ")
  100.                 rating_float = float(rating)
  101.                 story_manager.story.rating = rating_float
  102.                 break
  103.  
  104.             elif action == "quit":
  105.                 rating = input("Please rate the story quality from 1-10: ")
  106.                 rating_float = float(rating)
  107.                 story_manager.story.rating = rating_float
  108.                 exit()
  109.  
  110.             elif action == "nosaving":
  111.                 upload_story = False
  112.                 story_manager.story.upload_story = False
  113.                 console_print("Saving turned off.")
  114.  
  115.             elif action == "help":
  116.                 console_print(instructions())
  117.  
  118.             elif action == "save":
  119.                 if upload_story:
  120.                     id = story_manager.story.save_to_storage()
  121.                     console_print("Game saved.")
  122.                     console_print("To load the game, type 'load' and enter the following ID: " + id)
  123.                 else:
  124.                     console_print("Saving has been turned off. Cannot save.")
  125.  
  126.             elif action =="load":
  127.                 load_ID = input("What is the ID of the saved game?")
  128.                 result = story_manager.story.load_from_storage(load_ID)
  129.                 console_print("\nLoading Game...\n")
  130.                 console_print(result)
  131.  
  132.             elif len(action.split(" ")) == 2 and action.split(" ")[0] == "load":
  133.                 load_ID = action.split(" ")[1]
  134.                 result = story_manager.story.load_from_storage(load_ID)
  135.                 console_print("\nLoading Game...\n")
  136.                 console_print(result)
  137.  
  138.             elif action == "print":
  139.                 print("\nPRINTING\n")
  140.                 print(str(story_manager.story))
  141.  
  142.             elif action == "revert":
  143.  
  144.                 if len(story_manager.story.actions) is 0:
  145.                     console_print("You can't go back any farther. ")
  146.                     continue
  147.  
  148.                 story_manager.story.actions = story_manager.story.actions[:-1]
  149.                 story_manager.story.results = story_manager.story.results[:-1]
  150.                 console_print("Last action reverted. ")
  151.                 if len(story_manager.story.results) > 0:
  152.                     console_print(story_manager.story.results[-1])
  153.                 else:
  154.                     console_print(story_manager.story.story_start)
  155.                 continue
  156.  
  157.             else:
  158.                 if action == "":
  159.                     action = ""
  160.                     result = story_manager.act(action)
  161.                     console_print(result)
  162.  
  163.                 elif action[0] == '"':
  164.                     action = "You say " + action
  165.  
  166.                 else:
  167.                     action = action.strip()
  168.                     action = action[0].lower() + action[1:]
  169.  
  170.                     if "You" not in action[:6] and "I" not in action[:6]:
  171.                         action = "You " + action
  172.  
  173.                     if action[-1] not in [".", "?", "!"]:
  174.                         action = action + "."
  175.  
  176.                     action = first_to_second_person(action)
  177.  
  178.                     action = "\n> " + action + "\n"
  179.  
  180.                 result = "\n" + story_manager.act(action)
  181.                 if len(story_manager.story.results) >= 2:
  182.                     similarity = get_similarity(story_manager.story.results[-1], story_manager.story.results[-2])
  183.                     if similarity > 0.9:
  184.                         story_manager.story.actions = story_manager.story.actions[:-1]
  185.                         story_manager.story.results = story_manager.story.results[:-1]
  186.                         console_print("Woops that action caused the model to start looping. Try a different action to prevent that.")
  187.                         continue
  188.  
  189.                 if player_won(result):
  190.                     console_print(result + "\n CONGRATS YOU WIN")
  191.                     break
  192.                 elif player_died(result):
  193.                     console_print(result)
  194.                     console_print("YOU DIED. GAME OVER")
  195.                     console_print("\nOptions:")
  196.                     console_print('0) Start a new game')
  197.                     console_print('1) "I\'m not dead yet!" (If you didn\'t actually die) ')
  198.                     console_print('Which do you choose? ')
  199.                     choice = get_num_options(2)
  200.                     if choice == 0:
  201.                         break
  202.                     else:
  203.                         console_print("Sorry about that...where were we?")
  204.                         console_print(result)
  205.  
  206.                 else:
  207.                     console_print(result)
  208.  
  209.  
  210. if __name__ == '__main__':
  211.     play_aidungeon_2()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top